what is the correct way to read from a datarow if the cell might be null

leora picture leora · Nov 21, 2009 · Viewed 9.3k times · Source

I have the following code which seems to blow up if the column in the datarow (dr) is null. what is the correct way to parse out the value from the data row and handle null checks?

Person person = new Person()
{
    FirstName = dr["FirstName"].ToString(),
    LastName = dr["LastName"].ToString(),
    BusinessPhoneNumber = dr["BusinessPhone"].ToString(),

Answer

João Angelo picture João Angelo · Nov 21, 2009

If the column is of type string, but is nullable, what about trying:

// FirstName must allow null
FirstName = dr["FirstName"] as string

or

// FirstName would be empty for a NULL in the database
FirstName = (dr["FirstName"] as string) ?? string.Empty