by

Fixed/Sticky Headers on ASP.NET GridView using jQuery

The GridView control in ASP.NET Web Forms is an extremely useful and quick way of getting data out to the user in a nice tabular format. It does have one weak spot though and that is some of the tags it uses when doing this. Specifically, not putting the header information inside a <thead> tag.

So why is this important?

When you have a LOT of rows (as some do) after you’ve scrolled down the page and the table headers are out of view you can forget which column is which, especially if the data is similar (such as lots of numbers).

A quick and easy solution to this is to use a jQuery “sticky” or “fixed” table header plugin such as jquery.floatThead.

The problem comes in when you try and apply one of these plugins to a GridView. Since the GridView doesn’t use the <thead> tag the plugins often can’t find the header information which they are supposed to be fixing at the top of the screen after the user has scrolled down, as a result they just don’t work.

The Solution

There a two options to fixing this problem. The first is to use the DataBound event to change the header row to actually be a header row (why this isn’t the default I don’t know). The second option is to use a JavaScript/jQuery fix to make the first row in the table a table header.

In this case we’ll be using jQuery to fix the table to make it compatible with other jQuery plugins.

I stumbled upon a JavaScript fix by Rick Strahl which I wrapped up in a jQuery GridView Fix plugin so that it fit in with the rest of the project.

After either fix has been applied the table should now be compatible with other jQuery plugins.

Any tables also start to take on correct styling from CSS frameworks such as Bootstrap which also use the <thead> tag.