Tuesday, January 29, 2008

ASP .NET DataGrid with fixed headers

When dealing with data grid in ASP .NET, a very common design request for it is having a data grid which has a horizontal scrollbar and fixed column header.

Adding a Scrollbar
A vertical scrollbar is very useful when your data grid contains of many rows that cannot fit into a web page. This can be done by using DIV tag. Enclose your data grid into a <div> tag and set the overflow style to scroll or auto. Look at the example as below:

<DIV id=”div-datagrid” style=”OVERFLOW: auto;”>
    <asp:datagrid runat=server….> </asp:datagrid>
</DIV>
Fixed Header
A fixed header will stick on the top of your data grid and never scroll out of view, in this case, users will not get confuse which column represent which field.

To achieve this, add a style as below in your CSS file.

<style type="text/css">
<!--
.DataGridFixedHeader {
    FONT: menu;
    COLOR: black;
    background-color: #CCFFCC;
    position:relative;
    top:expression(this.offsetParent.scrollTop);
}
-->
</style>
Add this CSS class in your HeaderStyle’s CssClass. And now you can see the header is always on the top of your data grid.

But if the header moves a little bit down when you scroll the data grid (which will show something (text or line) on the top of the header), you can add “-2” after the scrollTop.

position:relative;
top:expression(this.offsetParent.scrollTop-2);
But this only works fine in IE but not Firefox. So if you are using Firefox, you have to find another way to implement it.

Hope you will find this helpful.

3 comments:

Anonymous said...

Not working in IE7 for me

xiaoyu on January 9, 2009 at 3:58 PM said...

Hi, I found this article in CodeProject.com but I personally haven't test it out yet. For your reference anyway -> Freezing ASP.Net Grid View Header With JavaScript and CSS

Anonymous said...

It was extremely interesting for me to read the blog. Thanks for it. I like such topics and everything connected to this matter. I definitely want to read a bit more soon.

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template