Reputation: 26517
How could we handle null for a datetime field (got from SQL Server) in our program in c#?
Upvotes: 6
Views: 8168
Reputation: 55082
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"];
}
Upvotes: 3
Reputation: 1062790
There are 3 common approaches here;
object
(perhaps as you fetch it from a data-reader), then DBNull.Value
can represent null. I don't tend to let this out of the data-layer, thoughDateTime.MinValue
is commonly interpreted as null
; a magic number, maybe - but it works and is supported by most data-binding etcNullable<T>
means you can use DateTime?
- i.e. a nullable-of-DateTime; just use DateTime?
where-ever you mean a DateTime
that can be null, and you can give it a value of null
or a valid DateTime
.Some other thoughts on data-access and nulls:
SqlCommand
you must use DBNull.Value
, not null
- see belowreader.IsDbNull(ordinal)
command stuff (with Nullable<T>
as the example):
param.Value = when.HasValue ? (object)when.Value : DBNull.Value;
Upvotes: 12