Freezing Datagrid Header/Columns Made Easy

You have already known how to make you long datagrid scrollable, however, when you scroll the grid, the header of the datagrid scrolls away. To make scrollable datagrid more user friendly, you may want to "freeze" the header while scrolling, and sometimes you may need to "freeze" your columns like Excel Spreedsheet. There are some third party components around to help you to implement these, and I believe those components used javascript heavily, it will take lots of time to develop such component if you decide to do it your own. My solution is pretty easy with only couple lines of code, the con is that it only works with IE 5 & up, becase I used CSS Expression which is used to assign a JavaScript expression to a CSS property, and it was first introduced in IE 5.
Freeze Header:
1. Define class .Freezing in Stylesheet:
.Freezing
{
   position:relative ;
   top:expression(this.offsetParent.scrollTop);
   z-index: 10;
}
2. Assign Datagrid Header's cssClass to Freezing
<HeaderStyle ... CssClass= "Freezing" ...></HeaderStyle>

3. You are done!

Freeze Columns:
1. Define class .FreezingCol in Stylesheet:

.FreezingCol
{
   LEFT: expression(document.getElementById("freezingDiv").scrollLeft);
   /*freezingDiv is the name of the div to make your datagrid scrollable */ 
   POSITION: relative;
   z-index: 1;
}

2. Assign Columns' cssClass to FreezingCol
If you have templateColumn, you can simply assign cssClass of the column to freezingCol. If you create the columns dynamically, you can assign the cssClass at runtime within ItemCreated event. For example:

e.Item.Cells(0).CssClass = "FreezingCol"
e.Item.Cells(1).CssClass = "FreezingCol"

3. You are done! Please keep in mind this solution only works with IE5 & up. To make cross browser solution, you need to use javascript which is out of scope of this article.

Happy Programming!

你可能感兴趣的:(datagrid)