如何让Gridview渲染THEAD?

And*_*ock 111 .net c# asp.net gridview

如何让GridView控件呈现<thead> <tbody>标签?我知道.UseAccessibleHeaders让它<th>代替<td>,但我不能让它<thead>出现.

Phi*_*ins 186

这应该这样做:

gv.HeaderRow.TableSection = TableRowSection.TableHeader;
Run Code Online (Sandbox Code Playgroud)

  • `HeaderRow`属性将为`null`,直到`GridView`已经被数据绑定,因此在运行上面的代码行之前一定要等到数据绑定发生. (68认同)
  • 正如下面的评论,至少在绑定后的ASP.NET 4.5还不够晚 - 但是它适用于OnPreRender. (6认同)

小智 24

我在OnRowDataBound事件中使用它:

protected void GridViewResults_OnRowDataBound(object sender, GridViewRowEventArgs e) {
    if (e.Row.RowType == DataControlRowType.Header) {
        e.Row.TableSection = TableRowSection.TableHeader;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是唯一对我有用的解决方案.谁设计了这些可怕的控件? (7认同)
  • 我将您的代码插入OnRowCreated事件并使其正常工作. (2认同)

ASa*_*lvo 10

答案中的代码需要继续Page_LoadGridView_PreRender.我把它放在一个被调用的方法之后Page_Load得到了一个NullReferenceException.

  • 你也可以放入`DataBound`事件.`grid.DataBound + =(s,e)=> {grid.HeaderRow.TableSection = TableRowSection.TableHeader; };` (4认同)
  • 不知道.NET 4.5现在是否有所不同......但我在_DataBound和_PreRender事件处理程序中都得到HeaderRow为null.这可能与我在gridView中使用ASP.NET Web Forms新的"模型绑定"功能有关. (4认同)

Mik*_*Vee 7

我使用以下代码执行此操作:

if我添加的陈述很重要.

否则(取决于渲染网格的方式),您将抛出以下异常:

该表必须按标题,正文和页脚的顺序包含行部分.

protected override void OnPreRender(EventArgs e)
{
    if ( (this.ShowHeader == true && this.Rows.Count > 0)
      || (this.ShowHeaderWhenEmpty == true))
    {
        //Force GridView to use <thead> instead of <tbody> - 11/03/2013 - MCR.
        this.HeaderRow.TableSection = TableRowSection.TableHeader;
    }
    if (this.ShowFooter == true && this.Rows.Count > 0)
    {
        //Force GridView to use <tfoot> instead of <tbody> - 11/03/2013 - MCR.
        this.FooterRow.TableSection = TableRowSection.TableFooter;
    }
    base.OnPreRender(e);
}
Run Code Online (Sandbox Code Playgroud)

this对象是我的GridView控件.

我实际上覆盖了Asp.net GridView来制作我自己的自定义控件,但你可以将它粘贴到你的aspx.cs页面并按名称引用GridView而不是使用custom-gridview方法.

仅供参考:我没有测试过页脚逻辑,但我知道这适用于Headers.


小智 5

这对我有用:

protected void GrdPagosRowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.TableSection = TableRowSection.TableBody;
    }
    else if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.TableSection = TableRowSection.TableHeader;
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.TableSection = TableRowSection.TableFooter;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在 VS2010 中尝试过的。