Pranay Rana: March 2010

Tuesday, March 16, 2010

Fixing Header of GridView or HtmlTable

In web project there is always problem when no of record is more and you have to scroll vertically to view all record. Your header of the Gridview or HtmlTable always go up when you are scrolling down to see all records so that you can not map the row data with the column easily without scrolling up.

So to resolve this problem you must fix out the header of the Gridview or HtmlTable when you are scrolling down. Below is the code to do this i.e to fix Header.

Create Style sheet :


div#gridPanel 
{
   width:900px;
   overflow:scroll;
   position:relative;
}


div#gridPanel th
{  
   top: expression(document.getElementById("gridPanel").scrollTop-2);
   left:expression(parentNode.parentNode.parentNode.parentNode.scrollLeft);
   position: relative;
   z-index: 20;
  }


top: expression(document.getElementById("gridPanel").scrollTop-2);
left: expression(parentNode.parentNode.parentNode.parentNode.scrollLeft); 
Above line of code Gives the Top and Left coordinates of the TH tag which will be generated for the Header inside the Gridview or HtmlTable. We are using the expression tag to dynamically assign the values through JavaScript when you scroll down. 

Z-index: 20
This line of css class cause the the header row to remain on top with respect to the normal rows.


Aspx Page

So after adding style sheet your aspx page look like below.

<div height="200px" id="gridPanel" runat="server" scrollbars="Auto" width="100px">
asp.net grid view
</div>


Right now its id specific but you can use this for multiple gridview or htmltable by using Jquery.