ASP.Net WebForms GridView table header 行在 thead - 排序后

ASP.Net WebForms GridView table header row in thead - when sorted

我正在对旧 ASP.Net WebForms 应用程序的 UI 进行现代化改造。我使用 Bootstrap 3 来完成这个。大多数控件都很容易重新设计样式,但 GridView 控件会带来一些麻烦。 Bootstrap 需要 table header 位于 thead 部分,但 GridView 控件在 table body 部分内呈现 header。 我能够使用以下代码强制 GridView 在 thead 元素内呈现 header:

public class AdvancedGridView : GridView
{
    #region Overrides of GridView

    protected override void OnPreRender( EventArgs e )
    {
        if ( ( ShowHeader && Rows.Count > 0 ) || ShowHeaderWhenEmpty )
            HeaderRow.TableSection = TableRowSection.TableHeader;
        if ( ShowFooter && Rows.Count > 0 )
            FooterRow.TableSection = TableRowSection.TableFooter;

        base.OnPreRender( e );
    }

    #endregion
}

但是我还有一个问题。一旦用户按任何列对 table 进行排序,GridView 控件将再次呈现并将 header 移动到 table body 元素内。

如何让 GridView 在用户排序时在 thead 元素中呈现它的 header?

我希望我知道为什么,但显然 OnPreRender 事件并不总是触发。

我发现将以下内容放置在您的 gridview 的 RowDataBound 事件中始终有效。

if (e.Row.RowType == DataControlRowType.Header) 
  e.Row.TableSection = TableRowSection.TableHeader;

这还有一个额外的好处,就是不必检查代码来查看是否有行,因为事件只会在有行时触发。