views:

3351

answers:

5

Hi,

I have an ASP.NET 2.0 (C#) web app, and in it I have a gridview that gets its data from an oracle database.

I want to know how to check if the gridview is empty, and the do something.

I have already tried:

if(GridView.Rows.Count == 0)
{
// Do Something
}

but it doesn't work...

Any ideas?

Thank you.

+3  A: 

If you're using databinding, the the row count of the datasource not the count on the grid itself.

Justin Niessner
+6  A: 

This doesn't work since the GridView is data bound and is going to fetch the actual data at a later time while rendering the page. You should check this by directly querying the data binding source of the gridview (see if the actual list that's grid view bound to is empty or not).

If you just want to display something when it's empty, you should use <EmptyDataTemplate> in your markup:

<asp:GridView runat="server">
<EmptyDataTemplate>The grid is empty</EmptyDataTemplate>
</asp:GridView>
Mehrdad Afshari
+1 -the EmptyDataTemplate is the most elegant solution IMHO
marc_s
+1 You can also use the EmptyDataText property
jmein
+2  A: 

Your code should work. But only after GridView.DataBind() has been called. Generally I don't check the GridView it's self, but the datasource of the grid view.

DataTable data = DAL.getdata();
if (data.Rows.Count == 0)
{
    ShowEmptyData();
}
else
{
    Grid.DataSource = dt;
    Grid.DataBind();
}
Al W
+3  A: 

I agree with the other responses. I want to add little information, you should get rows.count after databind method :

int rowCount = GridView.Rows.Count; // returns zero

GridView.DataBind();

rowCount = GridView.Rows.Count; // returns actual row count
Canavar
Just a little more info: the gridview will show only the max number of rows for paging if paging is enabled. So it is best to check the actual datasource
jmein
good point, thanks.
Canavar
A: 

DataTable data = DAL.getdata(); if (data.Rows.Count = 0) { ShowEmptyData(); } else { Grid.DataSource = dt; Grid.DataBind(); }