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.

CSS Friendly ASP.Net Adapter updates to GridView, DetailsView, and FormView

If you’ve used the CSS Friendly ASP.Net Control Adapters in the past, you may want to check out change set 9278, which included a number of improvements to the GridView, DetailsView, and FormView controls.

From the check-in notes:

– Major rewrites of GridView, DetailsView, and FormView walkthroughs
– FormView and DetailsView now use PagerTemplate when it exists
– FormView, DetailsView, and GridView properly position pager based on PagerPosition and Visibile properties
– Implemented GridView’s DataControlRowType.Pager instead of hard-coded CSS class (non-breaking change)

The new test “walkthru” pages are quite useful. You can now set the control options and see the results of the change immediately without having to modify the code in the ASPX file. Implementing the test pages this way made it much easier to evaluate if the control adapters were doing what they were supposed to do.