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(),
IsNull(DataColumn, DataRowVersion) Gets a value that indicates whether the specified DataColumn and DataRowVersion contains a null value.
You use DataTable's NewRow method to return a DataRow object of data table, add values to the data row and add a row to the data Table again by using DataRowCollection's Add method.
To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.
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
I believe, the data cell beeing null cannot be the reason for your problem. Maybe the column doesn't exist, or any other error happened, or the DataRow itself is null and you should handle that. Look at the exception - "seems to blow up" is not a valid description of your problem.
The following explains that, but will also answer the question from the title for everyone else.
If the column value is null, an object System.DBNull
is returned, and .ToString()
returns an empty string, while (string)
or as string
return null
.
So it makes no sense to check the returned item for ==null
because that won't ever evaluate to true
.
DBNull
case.null
, change .ToString()
to as string
.if (dr.IsNull("FirstName"))
or do ==null
on the target variable after the as string
.dr["FirstName"].ToString()
will occasionally throw null pointer exceptions because you're trying to access ToString
on a null object. Other than that, strings can be null, so really, if you know it's a string, and you don't mind that it's null, it'd be safe to do
FirstName = (String) dr["FirstName"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With