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?
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;
}
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With