Reputation: 753
I have the following code which I am trying to get data from the database for a Nullable DateTime Field in SQL Server -
If dr("SendDate") Is DBNull.Value Then
ctrl_prov_dtl.SelectedDateSendDate = DirectCast(Nothing, System.Nullable(Of DateTime))
Else
ctrl_prov_dtl.SelectedDateSendDate = dr("SendDate")
End If
This is calling the following Public Property
Public Property SelectedDateSendDate() As Nullable(Of DateTime)
Get
Dim myDateTime As DateTime
If (DateTime.TryParse(calSendDate.Text, myDateTime)) Then
Return calSendDate.Text
Else
Return "01/01/1900"
End If
End Get
Set(value As Nullable(Of DateTime))
calSendDate.Text = value
End Set
End Property
I keep getting the following error Nullable object must have a value.
I am really confused because I am setting the value to a Nullable(Of DateTime)
Upvotes: 2
Views: 3288
Reputation: 10478
It's likely because you are trying to set the text value of calSendDate
to value
regardless if it's null or not.
Instead, change your property setter to this:
Set(value As Nullable(Of DateTime))
If value.HasValue Then
calSendDate.Text = value
Else
calSendDate.Text = Nothing
End If
End Set
Additional advice:
If your project is .NET 3.5 or above and references System.Data.DataSetExtensions.dll, change your first block of code to this instead:
ctrl_prov_dtl.SelectedDateSendDate = dr.Field(Of DateTime?)("SendDate")
Also, your property getter never returns the parsed myDateTime
value. And returning 1/1/1900 as the fallback value on a nullable type feels very wrong to me.
Upvotes: 1