Jose Fernandez wrote:
Hello.
how can i cast a null value from a datareader (System.DBNull) to dateTime
I have an object. One of its fields is a DateTime type field. From the
database i am getting System.DBNull values from its corresponding column.
What can I do to cast it? i don't want to implement a custom method for
this.
myClass.ExpirationDate=Convert.ToDateTime(dr["ExpirationDate"]); // throw
an exception.
Object cannot be cast from DBNULL to other types.
You can't. You'll need to come up with some way to represent in your object
the fact that you received a null value from the database. If you are using
..NET 2.0 one option is to make your DateTime in your object a nullable type.
Do this by putting a question mark after the type in the declarations. Ex:
DateTime? date;
This makes the type nullable. Then instead of doing a Convert.ToDateTime
you would need to do a little logic.
if (Convert.IsDBNull(dr["ExpirationDate"]))
myClass.ExpirationDate = null;
else
myClass.ExpirationDate = Convert.ToDateTime(dr["ExpirationDate"]);
Then when reading you would want to check to make sure it has a value before
reading the value.
if (myClass.ExpirationDate.HasValue)
// work with the value
else
// it's null
--
Tom Porterfield