1
votes

I’m modernizing the UI of an old ASP.Net WebForms application. I make use of Bootstrap 3 to accomplish this. Most controls are easy to restyle but the GridView control makes some trouble. Bootstrap needs the table header to be in the thead section, but the GridView control renders the header inside the table body section. I was able to force GridView to render the header inside a thead element using this code:

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
}

But I still have a problem. As soon as the user sorts the table by any column, the GridView control will render again and move the header inside the table body element.

How can I make GridView render its header inside a thead element when it gets sorted by the user?

1
I don't know how you are doing your sort, and I've never used PreRender, but I've always found success with this in the RowDataBound event: if (e.Row.RowType == DataControlRowType.Header) e.Row.TableSection = TableRowSection.TableHeader; - Daniel
Thank you very much! This solution works perfectly for me. If you add it as answer I will accept it as the correct solution. - musium

1 Answers

2
votes

I wish I knew why, but apparently the OnPreRender event does not always trigger.

I've found the following to always work placed within the RowDataBound event of your gridview.

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

This also has the added advantage of not having to check in your code to see if there are rows as the event will only fire if there are.