In an earlier FAQ, Creating a Scrollable DataGrid, we saw how to create a scrollable DataGrid. However, when scrolling through the DataGrid, the header columns would not be visible, since they were not fixed. Ideally, when displaying a scrollable DataGrid we want to be able to have the header columns fixed, and only the body of the DataGrid scroll.
This can be accomplished with the ASP.NET DataGrid by surrounding the DataGrid with a div tag whose
overflow style attribute is set to auto or scroll, as we saw in the
previous FAQ. However, to have fixed headers, what we do is hide the scrollable DataGrid's headers (by setting the DataGrid's
ShowHeader property to False), and then create an HTML table immediately before the div
tag and scrollable DataGrid that displays the columns.
If this seems a bit confusing, don't worry. Let's check out an example to see how this can be handled.
|
Note that first, a standard HTML table is used to display the values of the header (FAQ ID, Question, and Views).
Then, a scrollable DataGrid is displayed, with its ShowHeader property set to False. The result is a scrollable DataGrid
whose "header column" is fixed. (I put header column in quotes because it's really an HTML table that is being displayed
as the header column, not the DataGrid's actual header.)
Off By a Bit
Unfortunately, as you can see in this live demo, the header column doesn't
line up perfectly with the DataGrid. This is because the displayed scrollbar pushes over the content of the DataGrid just a bit. In
fact, if you remove the overflow: auto; style setting from the div tag, everything will line up just peachy.
I have not found out any way to get everything to line up precisely short of just tweaking the style properties of the
table that displays the "header column" so as to shift the header column over. Specifically, I found that shifting the
"header column" over 9 pixels to the left compensated for the extra room the scrollbar took up. To move the "header column" over 9
pixels, use the following style attributes in the HTML table: position:relative; left:-9px;.
With this change, the new code becomes:
|
You can check out the new results in this live demo. Note that the "header column" and DataGrid body line up nicely.
| What If Scrollbars Aren't Needed? |
Recall that with the overflow: auto setting, the scrollbars only appear if the DataGrid exceeds beyond the specified
height constraint. If you adjust the HTML table to always be shifted 9 pixels to the left, then the
"header column" and DataGrid will be nicely lined up if scrollbars are displayed, but will again be offset if scrollbars are not
needed. One way to overcome this is to always have scrollbars displayed via the overflow: scroll setting.
|
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.