Locked or Fixed Grid Header in ASP.NET to 2.0
Working on a web page I noticed that I couldn't find a property to control whether a grid's header scrolls or not--the tag. I began Googling for it and found several answers, most of which were long and convoluted. So, I re-invented the wheel--because some wheels are better--and got it down to a few lines of CSS (Cascading Styles) and alternatively code-behind. Since this is working with
Example A (ASP.NET 2.0):
1. Put a new ASP.NET panel control on the form
2. Add a style sheet
3. Use the fixedHeader for the CssClass property of the panel
4. Put a GridView (which is rendered as an HTML table) or an HTML table in the panel
5. The table header will pick up the "table th" subordinate style
6. Bind some data to the grid and you have a fixed header
You will have to adjust the top: statement the further down in the control tree the grid is nested. You can also use document.getElementById and that should be less error prone but slower.
/* style sheet */
.fixedHeader
{
overflow: auto;
height: 150px;
}
table th
{
border-width: 4px;
border-color: Black;
background-color: Gray;
position: relative;
top: expression(this.parentNode.parentNode.parentNode.scrollTop-1);
}
To fix the header using code behind assuming that you used an ASP.NET GridView 2.0, you don't need the styles above and you can write the code-behind to inject the styles manually.
protected void GridView1_DataBound(object sender, EventArgs e)
{
Panel1.Style.Add("overflow", "auto");
Panel1.Style.Add("height", "300px");
GridView1.HeaderRow.BackColor = System.Drawing.Color.Gray;
GridView1.HeaderRow.BorderColor = System.Drawing.Color.Black;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
cell.Style.Add("position", "relative");
}
The code and the style sheets do almost the same thing. Occasionally the header gets misplaced when the whole browser is resized or moved. I haven't resolved the issue yet but this should get you started.
