Monday, 4 August 2008

.NET Gridview default display is annoying!

We've recently got into using a Gridview to display some of our tabular data. It's really easy to use and has some cool features - with a few annoying exceptions...

I wanted to remove the border lines which I did using CSS at first. This was ok except in IE when the browser showed a border around aspects of the table. I checked the HTML coming from the Gridview and it surprised me there was no THEAD for the header elements.

I didn't think these 2 issues were related but they still needed fixing.
A quick google search and it looks like the default setup for Gridviews will cause these problems. It might only matter to a few of us but what if you want full control over the style and HTML? Luckily there is a fix!

Use the following code to override the base class OnPreRender and the border/grid lines that can be seen in IE will disappear. The final line will also cause the table to render a THEAD (in between header rows):

protected override void OnPreRender(System.EventArgs e)

this.GridLines = System.Web.UI.WebControls.GridLines.None;
this.CellSpacing = -1;
this.Attributes.Add("cellspacing", "0");
this.UseAccessibleHeader = true;