DateTime is a value type, and can only contain valid date/times. Typically the way this is handled is to check your value returned from teh database to see if it's DBNull.Value, and if so set the DateTime to a special value like DateTime.MinValue which represents Null.
Alternatively you can use DateTime? which is a nullable DateTime datatype and you can actually assign it null (regular .Net null, not DBNull).
DateTime foo;
if (row["SomeField"] == DBNull.Value) {
foo = DateTime.MinValue;
} else {
foo = (DateTime)row["SomeField"];
}
You can make this syntax a little bit nicer by creating an extension method on a DataRow like so:
public static void ToDateTime(this DataRow row, string columnName) {
if (row[columnName] == DBNull.Value) {
return DateTime.MinValue;
} else {
return (DateTime)row[columnName];
}
}
then you can rewrite the original code like this:
DateTime foo = row.ToDateTime("SomeField");