简体   繁体   中英

How to change GridView column header text in c# web form?

I want to change GridView column header text, because its automatically putting from MSSQL database. I tried this code:

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

    }

Now, this code only changing the the first Column Header text. I tried this too

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

    }

and the data table is not showing after applying these changes.

Where i am wrong? Please try to provide full code.

You have two ways to do that :

1 - change you select query like this :

 Select name as [YourNewName]

2 - Set the header text in a C# method :

 DataGridViewName.Columns[1].HeaderText = "YourNewName";

your provided code is execute totally fine. the error might be some other part. please provide the full code for better understanding.

Though you can access Header row by calling GridView1.HeaderRow properties.

As you calling RowDataBound Events, which is fired after every row bound. access the DataBound Events in this case which is only fire once after the entire Gridview Bound.

here is the full code.

aspx page:

<asp:GridView ID="GridView1" runat="server" OnDataBound="GridView1_DataBound">

Code behind:

protected void GridView1_DataBound(object sender, EventArgs e)
{
    GridView1.HeaderRow.Cells[0].Text = "AGENT ID";
    GridView1.HeaderRow.Cells[1].Text = "NAME";
}

Jason there is nothing Wrong with Your approach you just need to Assign GridView1_RowDataBound to your Gridview Like this

<asp:GridView ID="GridView1" runat="server" OnDataBound="GridView1_DataBound">

and you Event will be called and it will work fine for you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM