Handle database table with null dates using Nullable(Of Date)

I have a SQL Server table with several date columns that can be NULL and in fact are NULL .

I thought I was handling this correctly by using the .HasValue test before trying for the value of a nullable type. But apparently not because I'm getting an InvalidOperationException - Nullable object must have a value - when the getter in my class object tries to populate a textbox:

Public Class EventItem
    Private _AcknowledgeDate As Nullable(Of Date)
    Public Property AcknowledgeDate() As Date?
        Get
            Return _AcknowledgeDate
        End Get
        Set(ByVal value As Date?)
            If value.HasValue Then
                _AcknowledgeDate = value
            Else
                _AcknowledgeDate = Nothing
            End If
        End Set
    End Property

my constructor gets data from SQL server; here is the fragment from constructor:

Me.AcknowledgeDate = If(IsDBNull(theRdr("AcknowledgeDate")), Nothing, theRdr("AcknowledgeDate"))

When the above setter runs the date is Null and the private variable _AcknowledgeDate is set to Nothing .

When the code tries to assign something to the textbox, the getter code gets the exception here:

txtAcknowledgeDate.Text = thisEvent.AcknowledgeDate

I can make assign the textbox as follows: txtAcknowledgeDate.Text = Nothing

Despite reading quite a bit about this nullable type facility, I guess I am quite confused about how to implement nullable dates in VB.Net.


Your AcknowledgeDate is already Nothing , you're setting it yourself in the constructor. You don't need to specify that again in the Set function, in fact you're just saying "if the value is Nothing, then set it as Nothing", which is redundant.

I believe the problem is that you're trying to assign that object Nothing reference to the textbox .Text property and that results in the exception.

TextBox.Text expects a String I don't see the reason of using Nothing . Create a Function to handle the Nothing values and show an empty string instead. Plus, it gives you the freedom of formatting your date as you like.

something like

Function getDateText(ByVal d As Date?) As String
  If d.HasValue = False Then
     Return ""
  End If

  Return d.Value.ToString("D")
End Function

and then call it when you want to set txtAcknowledgeDate.Text

txtAcknowledgeDate.Text = getDateText(thisEvent.AcknowledgeDate)
链接地址: http://www.djcxy.com/p/42832.html

上一篇: 访问数据库中的UPDATE语句vb.net中的语法错误

下一篇: 使用Nullable(Of Date)处理空日期的数据库表