Creating a Scrollable DataGrid
By: Scott Mitchell | Created: 2003-05-10 | Last Updated: 2003-05-15



A common question on many of the newsgroups and online messageboards is, "How can I limit the amount of space that my DataGrid takes up on the Web page?" Perhaps the developer, for formatting purposes, wants only 200 vertical pixels of the DataGrid to be displayed. Any DataGrid content beyond this should be clipped from view, but accessible via scrolling.

This effect is simple to accomplish with just a touch of cascading stylesheet (CSS) magic. CSS contains an overflow property, that specifies how the contents of a element that overflows an area should be handled. Using a div tag, we can create a DataGrid that's confined to a specified area on the screen like so:

<div style="vertical-align: top; height:200px; width:100%; overflow:auto;"> <asp:DataGrid runat="server" ...> ... </asp:DataGrid> </div>

View a Live Demo!

Weird Display in Internet Explorer 6.0
I have noticed Internet Explorer 6.0 sometimes places arbitrary whitespace between the start of the DataGrid and where the div tag appears in the HTML document unless you add the vertical-align: top; attribute in the div tag's style. Interestingly, Mozilla does not suffer from this anamoly. (Thanks to Mitais Woloski for this tip!)

That's all there is to it! Note that we can explicitly specify the height and width attributes in terms of pixels (px) or percentages. The overflow attribute should be set either to auto or scroll. auto displays a scrollbar only if the content is clipped (that is, the DataGrid extends beyond the specified height). With scroll, the scrollbar is displayed regardless of whether the DataGrid's height exceeds the specified height. (Be sure to check out the live demo!)

Creating a Scrollable DataGrid with a Fixed Header Column
In this FAQ 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. Another FAQ, Creating a Scrollable DataGrid with a Fixed Header, examines how to create a scrollable DataGrid with a fixed header column.


Home | FAQs | Articles | About | Buy the Book!

Copyright 2006, Scott Mitchell. All Rights Reserved.