使整数为空

时间:2010-09-02 15:45:38

标签: vb.net nullable

我有一个更新函数,它通过数据集更新sql server db表。表中的一个字段是整数并接受空值。因此,当我填充更新函数时,我需要一种在函数需要整数时输入null的方法。

我尝试这样做但_intDLocation = ""抛出异常

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

3 个答案:

答案 0 :(得分:33)

整数不能设置为Null。你必须通过在单词Integer之后添加一个问号来使整数“可为空”。现在_intDLocation不再是普通的整数。它是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

稍后,如果要检查null,可以使用这种方便可读的语法:

If _intDLocation.HasValue Then
   DoSomething()
End If

在某些情况下,您需要将值作为实际整数访问,而不是可以为空的整数。对于这些情况,您只需访问

_intDLocation.Value

阅读所有关于Nullable here的内容。

答案 1 :(得分:5)

试试这个:

Dim _dLocation As String = udDefaultLocationTextEdit.Text

Dim _intDLocation As Nullable(Of  Integer)

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

答案 2 :(得分:-1)

_intDLocation = Nothing