How Do I Determine if a Control Bound to a DataReader Has Any Rows?
If you use .NET Data Binding to bind data from a data source (like a DataSet) to a control (like a DataGrid or Repeater) you often want to know if the control contains any rows. You can then use this knowledge to, for example, hide the entire DataGrid and display a message with the text "No records found" instead. You can easily accomplish this with a DataSet, because you can retrieve the number of items in the DataSet using something like myDataSet.Tables[0].Rows.Count. But what if you use a DataReader like the SqlDataReader? This class does not expose a count property.... Fortunately, there is a way to work around this.
If all you're interested in is knowing if the DataReader contained at least one row, you can use the HasRows property of the DataReader. This property returns true if the DataReader has at least one row. You can use it to hide the DataGrid and display a label instead when the property is false, like this:
if (myDataReader.HasRows)
{
// At least one row; bind the grid
lblNoRecords.Visible = false;
myDataGrid.DataSource = myDataReader;
myDataGrid.DataBind();
}
else
{
// No rows found; hide the grid and display the label
myDataGrid.Visible = false;
lblNoRecords.Text = "No records found"
}
Note that the HasRows property is only available since .NET 1.1. So, for a solution that works in .NET 1.0, we'll need to think of alternative ways to accomplish this.
The next solution I am going to demonstrate will work in both .NET 1 and .NET 1.1. Even better, not only does it tell you if there are any records found, it will also tell you how many. All you need to do is request the Count property of the Items collection of the databound control after you have bound it to the DataReader, as in the following example:
myDataGrid.DataSource = myDataReader;
myDataGrid.DataBind();
if (myDataGrid.Items.Count > 0)
{
// At least one row; hide the label
lblNoRecords.Visible = false;
}
else
{
// No rows found. Hide the grid and display the label
myDataGrid.Visible = false;
lblNoRecords.Text = "No records found"
}
In this example, I simply used the Count property to see if there was at least one record. However, you can also use this code to display the number of records found on the label, like this:
lblNumRecords.Text = myDataGrid.Items.Count.ToString() +
" number of records found.";
Note that the Count property will return a useless value when you're using paging. When paging is enabled for the DataGrid control, the Count property returns the number of items currently displayed on the "page" of the control, which is always equal to the PageSize except for the last page. It will not return the number of items in the original datasource that the control is bound to.
Where to Next?
Wonder where to go next? You can read existing comments below or you can post a
comment yourself on this article.