I have a GridView which i programmatically bind using c# code. The problem is, the columns get their header texts directly from Database, which can look odd when presented on websites. So basically, i would like to modify the column header text, but programmatically. i have already tried the following,
testGV.Columns[0].HeaderText = "Date";
and
this.testGV.Columns[0].HeaderText = "Date";
does not seem to give me correct result.
I Think this Works:
testGV.HeaderRow.Cells[0].Text="Date"
You can do it with gridview's datarow bound event. try the following sample of code:
protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}
For more details about the row databound event study Thsi....
protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
#region Dynamically Show gridView header From data base
getAllheaderName();/*To get all Allowences master headerName*/
TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
txt_Days.Text = hidMonthsDays.Value;
#endregion
}
}
Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.
ASPX:
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="Date" DataField="CreatedDate" />
</Columns>
</asp:GridView>
CS:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
{
e.Row.Cells[i].Text = "Created Date";
}
}
}
}
On your asp.net page add the gridview
<asp:GridView ID="GridView1" onrowdatabound="GridView1_RowDataBound" >
</asp:GridView>
Create a method protected void method in your c# class called GridView1_RowDataBound
as
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "HeaderText";
}
}
Everything should be working fine.
Source: Stackoverflow.com