San Diego Website design home Contact Us Client Login


Sunday, September 16, 2007

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)
    {
        if (i.Equals(DBNull.Value))
        {
            return defaultvalue;
        }
        else
        {
            return i;
        }
    }

add data to the dataset (see other blog for instructions)

DataSet ds = new DataSet
adapter.Fill(ds);

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);

 Good Luck

Comments

Name
URL
Email
Email address is not published
Remember Me
Comments

CAPTCHA
Write the characters in the image above

San Diego Website Design
San Diego Flash Design
Testimonials
Contact Us
Support
Privacy Policy
Site Map