Handling NULL datetime values
Hi
How would I handle this.
The code is below
DateTime invoicedate = ((DateTime)invoiceReader["inv_date"]);
If the inv_date is returned NULL from the database I get the following error.
System.InvalidCastException: Specified cast is not valid.
Any ideas how to resolve this error?
VK
Re: Handling NULL datetime values
vb Code:
If invoiceReader.IsDBNull("inv_date") Then
'The inv_date column contains a null value.
Else
Dim invoiceDate As Date = CDate(invoiceReader("inv_date"))
End If
or:
vb Code:
Dim invoiceDate As Nullable(Of Date)
If invoiceReader.IsDBNull("inv_date") Then
invoiceDate = Nothing
Else
invoiceDate = CDate(invoiceReader("inv_date"))
End If
Re: Handling NULL datetime values
Re: Handling NULL datetime values
Now I'll answer in C#:
Code:
if (invoiceReader.IsDBNull("inv_date"))
{
// The inv_date column contains a null value.
}
else
{
DateTime invoiceDate = invoiceReader["inv_date"];
}
or:
Code:
Nullable<DateTime> invoiceDate;
if (invoiceReader.IsDBNull("inv_date"))
{
invoiceDate = null;
}
else
{
invoiceDate = invoiceReader["inv_date"];
}