A more elegant solution to display GridView header and footer when the data source is empty.
I think the need to always show the header and footer of a
GridView is pretty common.
When I first ran into this
problem, I went to Google and found lots of content about
this.
Some suggest tampering with the data source to
add an extra row if it’s empty.
Others show
overriding the CreateChildControls method.
I was not satisfied with either of these solutions. I didn’t
like that dirty feeling I had by tampering
with the
data source. And I didn’t like overriding the
CreateChildControls method because it
simply didn’t
work of me anyway. This solution only gave the appearance
of the header and
footer existing. I ran into issues
because I was programmatically adding controls to the
header.
Upon postback, if the data source was empty,
the control hierarchy would not be the same as
before
thus causing an error.
So here is my solution. I'll cover the main points of
interest and if you want to see more, I have
uploaded
all the source and example to the new MSDN Code Gallery.
http://code.msdn.microsoft.com/AlwaysShowHeaderFoot
Start out by extending the GridView control and add the
following structure.
The most important part here is
to override the PerformDataBinding method.
As you can see here. I am intercepting the data and making
sure there is at lease one row.
If there is, the
control behaves normally.
On the line with the red
arrow, I am checking if the binding source is a DataView.
If it is, I can just add a row here and be done with
it.
If the binding source is not a DataView (or
DataSet), then I fire an event that will need to be handled.
The event "MustAddARow", as seen here, will provide access
to the binding data and allow you to add a row.
Here is a snippet from a page where I handle the MustAddARow
event.
In this case, I am binding a List of Products
to the GridView.
As you can see, I'm just adding a new
Product to the list. It doesn't matter what data you add
here
because it will get hidden in back in the
GridView.
And finally back in the GridView, I override the OnDataBound
method so I can hide that extra row.
So there you have it. This is my first blog post ever.
Hopefully
someone will get some use out of this.
Thanks
-Joe