tags:

views:

41

answers:

2

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
+4  A: 

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
You may also want to catch the null string case; instead of comparing against an empty string literal, I'd use `String.IsNullOrEmpty()`.
tdammers
+1  A: 

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
Does the ? mark in VB?
Martin
The question mark is shorthand. Works in VB.NET although I generally don't see it used in many VB.NET examples online.
Larsenal
It was not valid syntax at first, but was added later: http://stackoverflow.com/questions/223844/history-of-vb-net-nullable-syntax
jball
I believe when nullable types were first introduced the `?` was not available in VB. However, at some point that ability was added.
Brian Gideon