ASP.NET GridView with fixed column headers

Technorati Tags: ,


 Requirement: GridView with fixed column headers that allow for scrolling horizontally and vertically. On page refresh or postback retain focus on the selected Gridrow.

Environment: Visual Studio 2005 and C# on Windows XP Professional SP2.

Solution: Add a web form to the web project. Then drop a panel onto the design view of the form. Adjust the height and width so as to force scrolling with the data displayed. Drop a GridView control onto the panel. I selected a style from the AutoFormat option. In the Column collection, add the Select command field and keep the "Auto-generate fields" checked.

Add a SQLDataSource control to the form and configure it to point a table/query with data rows. Set the GridView’s DataSourceID to the SQLDataSource control.

If you viewed the page in the browser, you should see something like this.

Update the panel properties, and set the scrollbars property to "Auto". The browser view should then look like this. But scrolling causes the column headers to disappear.

Add the following <style> block to the .aspx page.

    <style type="text/css">
        #grdvAuthors th
            text-align: center;
            position: relative;
            cursor: default;
        tbody th
            top: expression(document.getElementById("pnlAuthors").scrollTop-2); /* IE5+ only */
            z-index: 20;

And remove the following line from the .aspx designer source code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

This will now cause the column headers to stay fixed with horizontal and vertical scrolling.