views:

998

answers:

2

I've got a new instance of an object in a Linq DBML, but don't know of the test if the a date field is empty.

I have tried:

If d Is Nothing OrElse IsDBNull(d) OrElse d <= Date.MinValue Then
   TextValue = "nada"
Else
   TextValue = FormatDateTime(d)
End If

But the result is "12:00:00 am"

edit: Changed variable name the d
edit: Please note that the SQL field is nullable

edit II: Sorry guys, the error was in other part of the code. Comparing to nothing is the solution

+2  A: 

The code you want is (hopefully)..

If MyNullableDateObject.HasValue Then
   TextValue = FormatDateTime(MyNullableDateObject.Value)
Else
   TextValue = "nada"
End If

If the SQL field accepts Nulls then the Linq to SQL designer maps it to a .net Nullable type, for instance SQL DateTime will be mapped to the type called Date?. If you look at the properties of the field in the Linq to SQL designer it should have a property "Nullable" which, if the SQL schema allows NULLs in that field, will be set to true.

Non-Nullable (i.e. ordinary) date types are Value types not Object types so "Is Nothing" doesn't help. IsDBNull is for types under System.Data.SqlTypes, but Linq to SQL maps to "native" .Net types so that doesn't help either.

See - Nulllable Types


EDIT

You might consider renaming the variable Value to something else, (as I have done above) since of course, it isn't a Value type, Value is bad name.

Also Note that in VB Nullable type can be declared in two equivalent ways

Dim d As Date?
Dim d As Nullable(Of Date)

Hope this makes sense.

Christopher Edwards
Its actually value.value.I would also consider renaming 'value' ;p
Shawn Simon
Yeah, that's a good idea. Value isn't a value; that's the whole point!
Christopher Edwards
Adding HasValue throw a "Public member 'HasValue' on type 'String' not found" exception. Then, I think that String.IsNUllOrEmpty(d) will detect it, but no.
Eduardo Molteni
With the error I learn that d was a string, because in a previous function was formatted and the problem was there. Maybe I should delete the question.
Eduardo Molteni
I wouldn't delete the question, because all of this would have still happened if d was a date. But I leave it to you....
Christopher Edwards
A: 

I'm not sure if this will work, but you probably want to compare against Empty (or make a call to IsEmpty) as 12:00 am is NOT a null value.

casperOne