I'm trying to populate a class object with values from a database table. The someObject.Property
field is a nullable int type.
someObject.Property = Convert.ToInt32(dbReader["SomeField"]);
So, if SomeField
is null
, Convert
will give a DBNull
error. Is there a specific method I should be using for this?
This should work...
someObject.Property = dbReader["SomeField"].Equals(DBNull.Value)
? null
: (Int32)dbReader["SomeField"];
@John
- Good catch. Edit to reflect that oversight.
This method may be useful for what you're trying to do. It will try and parse the column value into it's respective type, and if it can't it will the return the types default value.
public T ParseValue<T>(System.Data.SqlClient.SqlDataReader reader, string column)
{
T result = default(T);
int index = reader.GetOrdinal(column);
if (!reader.IsDBNull(index))
result = (T)reader.GetValue(index);
return result;
}
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