Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the GridView Column Header Text - always returns blank

I have a GridView that I would like to get the Text of the columns headers from.

for (int j = 0; j < grdToDisplay.HeaderRow.Cells.Count; j++)
{
    string s = grdToDisplay.HeaderRow.Cells[j].Text.ToString(); //Returns ""
    s = grdToDisplay.HeaderRow.Cells[j].Text; //Returns ""
    s = grdToDisplay.Rows[0].Cells[j].Text; //Returns text from first row of results not the header
   // s = grdToDisplay.Columns[j].HeaderText.ToString(); // does not work as column count is 0
}

The GridView contents are generated at runtime based on a user query. The header is click-able to sort.

How can I loop the GridView and list the column header text?

like image 549
jimmy Avatar asked Jan 10 '13 14:01

jimmy


2 Answers

You can use GridViewColumn.HeaderText

for (int i = 0; i < grdToDisplay.Columns.Count; i++)
{
    string header = grdToDisplay.Columns[i].HeaderText;
}

Edit:

but this would give me no results as the columns count is 0

Then you have AutoGenerateColumns=true and only declaratively added columns are counted. So use this code after you have databound the GridView:

for (int i = 0; i < grdToDisplay.HeaderRow.Cells.Count; i++)
{
    string header = grdToDisplay.HeaderRow.Cells[i].Text;
}
like image 61
Tim Schmelter Avatar answered Oct 22 '22 05:10

Tim Schmelter


Since header of GridView is sortable, you can get the text of the header from Linkbutton. try this one: put the following code in the DataBind of the gridView:

for (int i = 0; i < gridView.HeaderRow.Cells.Count; i++)
            {

                if (gridView.HeaderRow.Cells[i].HasControls())
                {
                    //when gridview is sortable, type of header is LinkButton
                    // Linkbutton is in index 0 of the control
                    if (gridView.HeaderRow.Cells[i].Controls[0] is LinkButton)
                    {
                        LinkButton headerControl = gridView.HeaderRow.Cells[i].Controls[0] as LinkButton;
                       string headerName = headerControl.Text;

                    }

                }

            }
like image 28
Parsa Avatar answered Oct 22 '22 04:10

Parsa