How to handle the null value for the datetime allow-null (DB) field in our program?

How can we handle the null value for the datetime field (obtained from SQL Server) in our program in C #?

+6
null c # datetime
source share
2 answers

There are 3 general approaches here:

  • if you are talking about object (perhaps how you retrieve it from a data reader), then DBNull.Value can represent zero. I am not inclined to exclude this from the data layer, although
  • due to the history of .NET 1.1, DateTime.MinValue usually interpreted as null ; maybe a magic number, but it works and is supported by most data bindings, etc.
  • in .NET 2.0, Nullable<T> means you can use DateTime? - that is, the value nullable-of-DateTime; just use DateTime? , somewhere you mean a DateTime , which can be null, and you can give it a null value or a valid DateTime .

Some other thoughts on data access and zeros:

  • when going to SqlCommand you should use DBNull.Value , not null - below
  • when reading from a data reader, I try to check reader.IsDbNull(ordinal)

command material (with an example of Nullable<T> ):

 param.Value = when.HasValue ? (object)when.Value : DBNull.Value; 
+12
source share

Use DateTime?

What is your problem in particular?

- Change

It’s just so clear that the object is a Nullable DateTime, not a question :)

 DateTime? t = null; 

- Change

When replying to a comment, check it like this:

 DateTime? theTime; if( table["TheColumn"] == DBNull.Value ){ theTime = null; } else { theTime = (DateTime) table["TheColumn"]; } 
+3
source share

All Articles