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 o
You should do that in GridView's RowDataBound event which is triggered for every GridViewRow
after it 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>
I Think this Works:
testGV.HeaderRow.Cells[0].Text="Date"
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";
}
}
}
}
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
}
}
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....
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.