views:

72

answers:

3

I have an update function that updates an sql server db table through a dataset. One of the fields in the table is an integer and accepts null values. So when I am populating the update function I need a way to enter a null in when the function wants an integer.

I tried to do it this way but _intDLocation = "" throws an exception

Dim _dLocation As String = udDefaultLocationTextEdit.Text
    Dim _intDLocation As Integer
    If _dLocation <> "" Then
        _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
    Else
        'NEED HELP HERE
        _intDLocation = ""
    End If
+10  A: 

Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer. Now _intDLocation is no longer a normal integer. It is an instance of Nullable(Of Integer).

Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer?
If _dLocation <> "" Then
    _intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
    _intDLocation = Nothing
End If

Later on, if you want to check for null you can use this handy, readable syntax:

If _intDLocation.HasValue Then
   DoSomething()
End If

In some cases you will need to access the value as an actual integer, not a nullable integer. For those cases, you simply access

_intDLocation.Value

Read all about Nullable here.

Larsenal
+1 Totally forgot you can use `Integer?`. Nice and concise.
Jason Evans
To add to this otherwise excellent answer: _intDLocation will in reality be an instance of Nullable(Of Integer). See the documentation of Nullable here: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
Etienne de Martel
Thanks, Etienne. I'll add that in.
Larsenal
+1  A: 

Hi there.

Try this:

Dim _dLocation As String = udDefaultLocationTextEdit.Text

Dim _intDLocation As Nullable(Of  Integer)

If Not String.IsNullOrEmpty(_dLocation) Then
     _intDLocation = Integer.Parse(_dLocation)
End If

Cheers. Jas.

Jason Evans
A: 
_intDLocation = Nothing
lumberjack4