Thursday, July 24, 2008

How to Display ASP.NET GridView Header and Footer When No Data is Present?

The default behaviour of asp.net gridview is that it hides both Gridview header and footer when no data is present. You can note the absence of data (that is not a single row is available) by
putting text in EmptyDataTemplate of asp.net gridview.

---- other templates-----No data is present.<\EmptyDataTemplate>
<\asp:GridView>
But still you might want to show header and footer. What can we do? There exists a cheat! Just add an empty row to the datasource and bind your gridview to this datasource. Here goes the code.

DataTable table=new DataTable();
table=GetAllData(); //a function that fills the datatable
if(table.Rows.Count==0)
{
DataRow row = table.NewRow();
row[0] = "none";
table.Rows.Add(row);
gvTest.DataSource = table;
gvTest.DataBind();
}

Now it is nearly done! But one step is remaining. Now the first column of the first row will display "none". We do not want this. So we must hide it. How? Just create the RowDataBound event handler for your gridview.

---- other templates-----
No data is present.
<\EmptyDataTemplate>
<\asp:GridView>
Here goes the code for the rowdatabound event handler:

//invokes when a row is bound to data
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.Cells[0].Text=="none")
{
e.Row.Visible=false;
}
}
}

Note: You must explicitly enable footer to be shown. By default it is not shown. This way:
---- other templates-----
No data is present.
<\EmptyDataTemplate>
<\asp:GridView>
Now you are done. Happy programming!!

kick it on DotNetKicks.com

7 comments:

Anonymous said...

Hi. I like the post.I was just facing the problem. Your article helped me a lot. Thank you.

Tarok said...

this is very nice blog...
this is very helpful and attractive biog.
visit for asp.net help asp.net help

almny said...

thanks it's good idea
but how i can do it by using Linq ?

Anonymous said...

You forgot the row.BeginEdit()?

Yuri said...

Nice trick. Thank you

Anonymous said...

didnt help error no column 0 is found.

Anonymous said...

Hi.. Your post is nice but please Add the output of your program at the end so people who read your articles will get the complete picture.

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles