tags:

views:

68

answers:

2

How would I check for a null datetime value in a DataRow?

The following works with a dataReader.

calEventDTO.endTime = dr.IsDBNull(9) ? null : (DateTime?) dr.GetDateTime(9);

What is the equivalent when checking the following DataRow?

calEventDTO.endTime = (DateTime)row["endTime"];

Sorry for the very newbee question.

+1  A: 
calEventDTO.endTime = row["endTime"] != null ? (DateTime)row["endTime"] : null;

or even better

calEventDTO.endTime = row["endTime"] as DateTime;

PS. I'm assuming you are using C#, since you have not given any details about the language.

RaYell
You can't use the `as` operator with DateTime since it is a value type, and the `as` operator can be used only with reference types.
Fredrik Mörk
+1  A: 

Use Convert.IsDBNull:


calEventDTO.endTime = (DateTime?) (Convert.IsDBNull(row["endTime"]) ? null : row["endTime"]);
Alfred Myers
This worked with a little adjustment (added (DateTime?)) that ReSharper found for me.calEventDTO.recurrenceID = Convert.IsDBNull(row["recurrenceID"]) ? (DateTime?) null : (DateTime)row["recurrenceID"];
Chin
Yeah... I used your first snippet (which does not cast) as a base to mine. I've updated mine putting a cast on the result of the expression instead of casting each of the operands of the ternary operator.
Alfred Myers