JanOlMajti
JanOlMajti

Reputation: 1397

Check dataset is empty or not

This is working for me just fine. With if checks if dataset is empty or not. If so, return null value. But is the check of dataset right way or should i do some other way?

 da2 = new SqlDataAdapter("SELECT project_id FROM project WHERE _small_project_id = '" + cb_small_project.SelectedValue + "' ORDER BY NEWID()", conn);
 ds2 = new DataSet();
 da2.Fill(ds2);
 DataRow[] rowProject = dt2.Select();

 if (ds2.Tables[0].Rows.Count == 0)
    cmd.Parameters["@_project_id"].Value = guidNull;
 else
    cmd.Parameters["@_project_id"].Value = rowProject[0]["project_id"];

Upvotes: 11

Views: 38808

Answers (5)

Osama Rizwan
Osama Rizwan

Reputation: 615

This Worked for me.... and won't give exception....

foreach (DataTable table in ds.Tables)
   if (table.Rows.Count != 0)
      table.Dispose();

Upvotes: 2

manikandanlg
manikandanlg

Reputation: 11

try this

 if (((System.Data.InternalDataCollectionBase)(ds.Tables)).Count != 0)
{
}
else
{
}

above code will work

Upvotes: 1

joetheterm
joetheterm

Reputation: 41

You can use bool and return true. For all tables in dataset

bool IsEmpty(DataSet dataSet)
{
    foreach(DataTable table in dataSet.Tables)
    if (table.Rows.Count != 0) return false;

    return true;
}

Upvotes: 4

gimbar
gimbar

Reputation: 135

I'd try check for:
ds2.HasChanges()
It should be true if any data has been added. For further information check here.

Upvotes: 4

Rafał Warzycha
Rafał Warzycha

Reputation: 561

In my opinion the 'right' way is to check both:

ds2.Tables.Count 

ds2.Tables[0].Rows.Count

Upvotes: 17

Related Questions