我有一个更新函数,通过数据集更新sql server db表.表中的一个字段是整数并接受空值.所以,当我填充更新功能,我需要一种方法来进入当函数想要一个整数空.
我尝试这样做但 _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
Run Code Online (Sandbox Code Playgroud)
Lar*_*nal 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
Run Code Online (Sandbox Code Playgroud)
稍后,如果要检查null,可以使用这个方便,可读的语法:
If _intDLocation.HasValue Then
DoSomething()
End If
Run Code Online (Sandbox Code Playgroud)
在某些情况下,您需要将值作为实际整数访问,而不是可以为空的整数.对于这些情况,您只需访问
_intDLocation.Value
Run Code Online (Sandbox Code Playgroud)
在这里阅读所有关于Nullable的内容.
试试这个:
Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Nullable(Of Integer)
If Not String.IsNullOrEmpty(_dLocation) Then
_intDLocation = Integer.Parse(_dLocation)
End If
Run Code Online (Sandbox Code Playgroud)