How to change the Header Text of Gridview after Databound?

Can do this with RowDataBound event of GridView

protected void grdSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.Header)
     {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("_", " ");
        }
     }
}

and it works fine.


You can change the text of the cell rather than the HeaderText property:

        for (int i = 0; i < grdSearchResult.Columns.Count; i++)
        {
            grdSearchResult.HeaderRow.Cells[i].Text = grdSearchResult.HeaderRow.Cells[i].Text.Replace("_", "");
        }

You don't need to do this in PreRender, just after the data has been bound.


Set AutoGenerateColumns property of gridview to false and add BoundFields.

<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="false">
<columns>
<asp:BoundField HeaderText="ID" DataField="empNo" />
<asp:BoundField HeaderText="First Name" DataField="fName" />
<asp:BoundField HeaderText="Last Name" DataField="lName" />
</columns>
</asp:GridView>