Handling.Net DataSets correctly
Posted by CJ on March 18, 2009
One of the most common programming issues I see when working at clients locations is the way the common .Net DataSet is managed. I see a lot of code written like the first example below which checks if the DataSet table contains any rows. The problem with Example 1 is it expects a couple of things. Firstly that a DataSet (ds) even exists and secondly that it also contains a table. This code will throw an exception if the DataSet is null or no DataSet table exists.
Example 1
//this will throw an exception if ds is null or no table exists
if(ds.Tables[0].Rows.Count > 0)
{
//process data
}
Example 2
So you should write your code checking of empty rows, empty tables and if the DataSet object exists.
if(ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
//process data
}
else
{
// it is empty
}
Happy Coding!