How to check empty DataTable

I have a DataSet where I need to find out how many rows has been changed using the following code:

dataTable1 = dataSet1.Tables["FooTable"].GetChanges();

foreach (DataRow dr in dataTable1)
{
  // ...
}

DataSet has DataSet.HasRow but DataTable doesn't have such method. If there is no changed rows. changedDT1 will be a null value, causing the loop to throw exception.

How do I check if DataTable is empty? I tried Rows.Count - doesn't work...


Solution 1:

First make sure that DataTable is not null and than check for the row count

if(dt!=null)
{
  if(dt.Rows.Count>0)
  {
    //do your code 
  }
}

Solution 2:

If dataTable1 is null, it is not an empty datatable.

Simply wrap your foreach in an if-statement that checks if dataTable1 is null. Make sure that your foreach counts over DataTable1.Rows or you will get a compilation error.

    if (dataTable1 != null)
    {
       foreach (DataRow dr in dataTable1.Rows)
       {
          // ...
       }
    }

Solution 3:

Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.

if (DetailTable != null && DetailTable.Rows.Count>0)

Solution 4:

Don't use rows.Count. That's asking for how many rows exist. If there are many, it will take some time to count them. All you really want to know is "is there at least one?" You don't care if there are 10 or 1000 or a billion. You just want to know if there is at least one. If I give you a box and ask you if there are any marbles in it, will you dump the box on the table and start counting? Of course not. Using LINQ, you might think that this would work:

bool hasRows = dataTable1.Rows.Any()

But unfortunately, DataRowCollection does not implement IEnumerable. So instead, try this:

bool hasRows = dataTable1.Rows.GetEnumerator().MoveNext()

You will of course need to check if the dataTable1 is null first. if it's not, this will tell you if there are any rows without enumerating the whole lot.