Skip to main content
 首页 » 编程设计

c#之启用 gridview 排序时,在运行时更改 Gridview 中的列名称

2024年02月13日10lovecherry

我想在运行时更改 gridview 的其中一列的名称。Gridview 还启用了排序。

GridView 看起来像:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" OnRowCreated="myGrid_Rowcreate"  
ShowFooter="false" 
AllowSorting="true" 
OnSorting="GridView1_Sorting" 
EnableViewState="false" 
ShowHeaderWhenEmpty="True" 
AllowPaging="false"> 
 
<AlternatingRowStyle CssClass="altrowstyle" /> 
<HeaderStyle CssClass="headerstyle" /> 
<RowStyle CssClass="rowstyle" /> 
<RowStyle Wrap="false" /> 
<HeaderStyle Wrap="false" /> 
</asp:GridView> 

我的 onRowCreate 函数如下所示:

  protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        GridViewRow gvr = e.Row; 
        if (gvr.RowType == DataControlRowType.Header) 
        { 
            gvr.Cells[1].Text = "test1"; 
        } 
    } 

列名称确实更改为 test1 但排序功能关闭。我应该怎么做才能更改列名称以及排序功能也保留?我的排序没有问题。只有当我写上面的内容时代码,该列的排序选项关闭。 请帮忙! 谢谢。

请您参考如下方法:

问题是因为排序在 GridView 列名称中设置了一个 LinkBut​​ton 控件,并按照您的方式设置名称,禁用该控件。因此,您必须使用如下代码设置列的名称:

((LinkButton)e.Row.Cells[1].Controls[0]).Text = "Test1";