Handle null Values in DataSet, DataTable
When working with datasets and datatables we will run into issues where the resulting column values are null in the database. These issues can cause your code to fail when you are using the values to make calculations or validations with the data. The easiest way to handle this is to zero the null value using a custom method call. The logic will also work with string values and here is how it works: object ZeroNull(object i, object defaultvalue) add data to the dataset (see other blog for instructions) DataSet ds = new DataSet choose a row in the dataset to work with. DataRow dr = ds.Rows[0]; Insert the column value into our new method to zero the null value if it is null otherwise it will return its actual value and cast it as a decimal. (decimal)x = (decimal)ZeroNull(dr["columnName"], 0m);
{
if (i.Equals(DBNull.Value))
{
return defaultvalue;
}
else
{
return i;
}
}
adapter.Fill(ds);
Good Luck


