views:

233

answers:

4

I'm modifying someone else's code where a query is performed using the following:

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
da.Fill(ds);

How can I tell if the DataSet is empty (i.e. no results were returned)?

+2  A: 

I would test if ds.Tables.Count = 0, because all a DataSet is is a collection of Tables with schema, right?

alternately, from the MSDN:

Return Value Type: System..::.Int32 The number of rows successfully added to or refreshed in the DataSet. This does not include rows affected by statements that do not return rows.

drachenstern
Dangit, @Tom, beat me to it...
drachenstern
This was my initial thought as well, but it doesn't work. There's still a table even if it's empty, so ds.Tables.Count==0 returns false even when there are no results.
MCS
+7  A: 

You don't have to test the dataset. The Fill() method returns the # of rows added. See MSDN

Tom
Wish I could use this, but the code which fills the dataset is part of a method which returns the filled dataset. The code I'm writing calls the method like this DataSet ds = GetResults(sql, conn).
MCS
Looping through tables and counting rows will definitely work, but check out the ExtendedProperties property of DataSet, which would allow you to set this kind of custom information from within GetResults() and use it upon return. Might not be applicable here but maybe in the future.
Tom
+3  A: 

If I understand correctly, this should work for you

if (ds.Tables[0].Rows.Count == 0)
{
    //
}
rosscj2533
I suppose that if the query used multiple tables, this wouldn't work properly.
MCS
Ah, but a simple loop over the count of tables grabbing the count of rows from each would be simple to code. I say toss that check in as well.
drachenstern
+3  A: 

You should loop through all tables and test if table.Rows.Count is 0

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

    return true;
}
SchlaWiener