Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check empty DataTable

Tags:

c#

ado.net

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...

like image 688
KMC Avatar asked Jun 07 '11 11:06

KMC


People also ask

Can DataTable be null?

If a DataTable is null then you can't copy anything to it: there isn't anything to copy into!


2 Answers

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    } } 
like image 100
Pranay Rana Avatar answered Sep 29 '22 05:09

Pranay Rana


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)        {           // ...        }     } 
like image 25
Ben Robinson Avatar answered Sep 29 '22 05:09

Ben Robinson