0

Can someone help me fix my code I am trying to put null in sql server through a function that is excepting _dtSWO.

If I set _dtSWO = Nothing it returns #12:00:00 AM# which throws an exception. The field is nullable in sql server I just want it to return a blank

Dim _swoDate As String = udSWOReceivedDateDateEdit.Text
        Dim _dtSWO As Date

        If _swoDate <> "" Then
            _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)
        Else
            'THIS DOESNT WORK
            _dtSWO = Nothing
        End If
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152

2 Answers2

4

You need to use a Nullable type. By default, Date does not except null (Nothing in VB.Net) as a value. Nullable types do accept null (Nothing).

    Dim _dtSWO As Nullable(Of Date)

    If String.IsNullOrEmpty(_swoDate) Then
        _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)
    Else
        _dtSWO = Nothing
    End If

Edited based on the comment.

Martin
  • 11,031
  • 8
  • 50
  • 77
  • 2
    You may also want to catch the null string case; instead of comparing against an empty string literal, I'd use `String.IsNullOrEmpty()`. – tdammers Sep 02 '10 at 16:03
1

Make it Nullable. Same kind of situation as your Nullable Integer question.

Dim _swoDate As String = udSWOReceivedDateDateEdit.Text
Dim _dtSWO As Date?

If _swoDate <> "" Then
    _dtSWO = Date.Parse(udSWOReceivedDateDateEdit.Text)
Else
    _dtSWO = Nothing
End If
Larsenal
  • 49,878
  • 43
  • 152
  • 220
  • The question mark is shorthand. Works in VB.NET although I generally don't see it used in many VB.NET examples online. – Larsenal Sep 02 '10 at 16:02
  • It was not valid syntax at first, but was added later: http://stackoverflow.com/questions/223844/history-of-vb-net-nullable-syntax – jball Sep 02 '10 at 16:04
  • I believe when nullable types were first introduced the `?` was not available in VB. However, at some point that ability was added. – Brian Gideon Sep 02 '10 at 16:09