Cleaning up the GridView’s EmptyDataTemplate (damn those tables!)

A project I’ve been working on makes frequent use of the ASP.Net GridView. However, as many people know, the GridView has one glaring issue: It wraps your <EmptyDataTemplate> in an HTML table — something that I don’t want, for two reasons:

  1. My empty data template does not consist of tabular data.
  2. My stylesheet has a default style for tables — a style that I don’t want applied to my empty data template.

One solution is to use the CSS Friendly Adapters for ASP.Net, which potentially solves both prolems, but that will bring in potential breaking changes to my GridView controls. I don’t have time for that (yet).

The solution I came up with is to do two things:

  1. Create a new CSS class that removes table formatting (borders, backgrounds, padding, margins, etc.). This class will be applied to the GridView only when it has no data.
  2. Add a line of code in the OnPreRender() method for each web page or control that has a GridView, conditionally setting the CSS class of the GridView to the aforementioned class.

My CSS class looks like the following.

.empty, .empty td { border:0;background:none;margin:0;padding:0; }

The line of code in your OnPreRender() event follows.

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    if (myGridView.Rows.Count == 0)
        myGridView.CssClass = "empty";
}

Why the OnPreRender stage? By placing your code here, you ensure that all data loaded into your GridView is already bound, whether it be from code (myGridView.DataBind()), from data sources in markup (such as the ObjectDataSource), or from viewstate.

It isn’t pretty, and it doesn’t give you semantic markup, but it’s easy enough to implement and can solve the visual problem.

One thought on “Cleaning up the GridView’s EmptyDataTemplate (damn those tables!)”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>