Sunday, December 13, 2009

How to Add a Locked Header Row to an ASP.NET GridView Control

The GridView control is often used to display tabular data, much like an Excel spreadsheet. However, unlike Excel, the GridView control doesn't have any automatic way of locking the header row so that it doesn't scroll out of view.

Check out this example of a GridView within a DIV with the overflow-Y property set to scroll. Notice that as you scroll the GridView, the header row scrolls out of view. It would be more convenient to have a locked header row so that the header row is always visible regardless of the scoll position of the GridView. It would also be nice to have a header row that dynamically configured itself as per the data source so that if we add a new field to the GridView, a corresponding column automatically gets added to the locked header row.

Here's another example, but this time, the header row stays locked at the top of the GridView so that you can scroll without losing track of column names. There are a few steps required to implement this functionality.

  1. Create a DIV on the page to contain the header row and set the DIV (either statically or dynamically) to the same width as the DIV that contains the GridView.
  2. Insert an ASP.NET Table control into the header DIV.
  3. In Page_Init, dynamically add the necessary cells to the header table and set the appropriate properties so that it matches the appearance of the rest of the GridView.
  4. Check for sortable columns and dynamically add sorting LinkButtons to the header row.
  5. Add code to handle the LinkButton's Click event and sort appropriately.

Let's go through each of these steps. (If you'd prefer to work with a working project, you can download the project at the end of this post.)

More info

No comments:

Post a Comment

Discovery Way Of Life

Back to TOP