简体   繁体   English

如何在C#Web表单中更改GridView列标题文本?

[英]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. 我想更改GridView列标题文本,因为它会自动从MSSQL数据库放入。 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 : 1-更改您选择的查询,如下所示:

 Select name as [YourNewName]

2 - Set the header text in a C# method : 2-在C#方法中设置标题文本:

 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. 尽管您可以通过调用GridView1.HeaderRow属性来访问Header行。

As you calling RowDataBound Events, which is fired after every row bound. 当您调用RowDataBound事件时,每行绑定后都会触发该事件。 access the DataBound Events in this case which is only fire once after the entire Gridview Bound. 在这种情况下访问DataBound事件,该事件仅在整个Gridview Bound之后触发一次。

here is the full code. 这是完整的代码。

aspx page: aspx页面:

<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 杰森(Jason)并没有错,您的方法只是需要Assign GridView1_RowDataBound to your Gridview

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

and you Event will be called and it will work fine for you 您的Event将被调用,它将为您正常工作

 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";
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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