@manhnguyenv

Welcome to my blog!

Change header text of columns in a GridView

January 7, 2019 18:04

Change header text of columns in a GridView (edit)

You should do that in GridView's RowDataBound event which is triggered for every GridViewRow afterit was databound.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Text = "Date";
    }
}

or you can set AutogenerateColumns to false and add the columns declaratively on aspx:

<asp:gridview id="GridView1" 
  onrowdatabound="GridView1_RowDataBound"
  autogeneratecolumns="False"
  emptydatatext="No data available." 
   runat="server">
    <Columns>
         <asp:BoundField DataField="DateField" HeaderText="Date" 
            SortExpression="DateField" />
    </Columns>
</asp:gridview>

How to get column name from gridview?

You can get it like this :

gv.HeaderRow.Cells[i].Text

Or like this :

gv.Rows[0].Cells[i].Text

Rows[0] should be your header row.

Try solution

string columnName = ((System.Web.UI.WebControls.DataControlFieldCell)(myGrid.Rows[0].Cells[i])).ContainingField.HeaderText;

 

Categories

Recent posts