I have a database that hold’s a user’s optional profile. In the profile I have strings, char (for M or F) and ints.
I ran into an issue where I try to put the sex of the user into the property of my Profile object, and the application crashes because it doesn’t know how to handle a returned null value.
I’ve tried casting the data to the appropriate type
char sex = (char)dt.Rows[0]['Sex'];
Which didn’t fix my problem. I then tried changing the types to Nullable and Nullable and get conversion issues all the same. My current solution that I was able to find is the following:
object.sex = null; if(dt.Rows[0]['Sex'] != DBNull.Value) object.sex = (char)dt.Rows[0]['Sex']; object.WorkExt = null; if(dt.Rows[0]['WorkExt'] != DBNull.Value) object.WorkExt = (int)dt.Rows[0]['WorkExt'];
Is there a simpler or better way to do this? Or am I pretty much on the right track?
rotard’s answer (use
Is<ColumnName>Null()) only works for typed data sets.For untyped data sets, you have to use one of the patterns in the following code. If this code isn’t definitive, let me know and I’ll edit it until it is. This is an extremely common question that there should really be only one right answer to.