joe joe - 4 months ago 22
Vb.net Question

vb.net Date equivalent to String.Empty

In my program, I am writing a class to read values in one database table, and copy them into another.
When reading string fields, I have a function that is called which checks whether or not the string value is null, and if it is, it returns an empty string, if not, it returns the string. (See code below)

I also have

datetime
fields which can contain nulls, and without a similar function, I get a runtime error when trying to copy them.

Is there an equivalent of the code below that I can use for entering in a blank date if the value in the database row is null?

Public Shared Function dbToString(o As Object) As String

If o Is DBNull.Value Then
Return String.Empty
Else
Return CStr(o)

End If
End Function

Answer

DateTime is a value type, therefore the notion of 'blank' doesn't exist. You could use the MinValue of DateTime but there might be problems with this and the intent might not be clear. Use a nullable DateTime instead:

Public Shared Function dbToDate(o As Object) As DateTime?
    If o Is DBNull.Value Then
        Return Nothing
    Else
        Return Convert.ToDateTime(o)
     End If
End Function
Comments