Question

I have DAL where I convert database null value to their equivalent representation in C#. For example:

NULL for Numeric = 0
NULL for String = String.Empty
NULL for DateTime = "1/1/0001" (i.e. DateTime.MinValue)

The problem, for date, lies in the presentation layer, especially in GridViews. You cannot show 1/1/01 to users.

What I used to do is check if myDate.Year=1 or myDate.Year < AcceptedDate and display empty string, but seems to be extra effort unlike other types

Please am open to better approach. Thanks.

Was it helpful?

Solution

Use Nullable datatype to store null value.

DateTime? value = null;
int? myNullableInt = 1;
value = DateTime.Now;

How to check whether variable has value or null

if (value!=null)

String value can store null, so there is no diffrent datatype for string to store null.

string var;
if (var == null)

or

if (String.IsNullOrEmpty(var))

OTHER TIPS

You can also use DateTime.MinValue constant.

http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx

Your conditions would be:

if (myDate == DateTime.MinValue)

You can use Nullable DateTime, so you will return DateTime? instead of DateTime from your DAL. This way you can check if returned value is null.

DateTime? dateTime = null;

As the others mention, you could use a System::Nullable<DateTime>.

The other approach I've seen is to use a standard DateTime and just use a special value such as DateTime.MinValue. This is useful if you need to honor an existing interface's types and can't change the DateTime to a Nullable<DateTime>.

You can either use a Nullable DateTime as the others suggested, or use this trick: (To prevent non valid defaults.)

// If dateTime has not been initialize, initialize to Now
// (or to any other legal inital values)
dateTime = ((dateTime != new DateTime()) ? dateTime : DateTime.Now);

This trick is useful if you have to use a non-nullable DateTime and want to provide a default if none. (E.g. you have a non-nullable DateTime column in a DB and want to set the value only if row is new.)

I don't think you have much choice but to make the check like you have been and display accordingly. A nullable type might make things easier for you. Depending on your data, even the numeric should be treated this way. DBNull != 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top