How could we handle null for a datetime field (got from SQL Server) in our program in c#?
+2
A:
Use DateTime?
What problem are you having, specifically?
-- Edit
Just so it's clear, that's a Nullable
DateTime object, not a question :)
DateTime? t = null;
-- Edit
Responding to comment, check it like so:
DateTime? theTime;
if( table["TheColumn"] == DBNull.Value ){
theTime = null;
} else {
theTime = (DateTime) table["TheColumn"];
}
Noon Silk
2009-08-29 09:01:20
I can not cast object (a column of DataRow) to DateTime .
odiseh
2009-08-29 09:20:08
Responded via edit. You just need to check if it is equal to `DBNull.Value`.
Noon Silk
2009-08-29 09:23:35
Oh found it Thank you.
odiseh
2009-08-29 09:37:38
solved it via using System.Convert.ToDateTime.
odiseh
2009-08-29 09:38:36
Okay ... You may like to post how you've solved it and mark it as accepted, so it helps anyone else who searches.
Noon Silk
2009-08-29 09:54:24
+7
A:
There are 3 common approaches here;
- if you are talking about
object
(perhaps as you fetch it from a data-reader), thenDBNull.Value
can represent null. I don't tend to let this out of the data-layer, though - due to .NET 1.1 history,
DateTime.MinValue
is commonly interpreted asnull
; a magic number, maybe - but it works and is supported by most data-binding etc - in .NET 2.0,
Nullable<T>
means you can useDateTime?
- i.e. a nullable-of-DateTime; just useDateTime?
where-ever you mean aDateTime
that can be null, and you can give it a value ofnull
or a validDateTime
.
Some other thoughts on data-access and nulls:
- when passing to a
SqlCommand
you must useDBNull.Value
, notnull
- see below - when reading from a data-reader, I tend to check
reader.IsDbNull(ordinal)
command stuff (with Nullable<T>
as the example):
param.Value = when.HasValue ? (object)when.Value : DBNull.Value;
Marc Gravell
2009-08-29 09:01:40