使整数为空 [英] Make An Integer Null
问题描述
我有一个更新函数,可以通过数据集更新 sql server db 表.表中的字段之一是整数并接受空值.因此,当我填充更新函数时,我需要一种方法来在函数需要整数时输入空值.
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.
我尝试这样做,但 _intDLocation = ""
抛出异常
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
推荐答案
整数不能设置为 Null.您必须通过在单词 Integer 后添加问号使整数可空".现在 _intDLocation 不再是一个普通的整数.它是 Nullable(Of Integer)
的一个实例.
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
稍后,如果你想检查 null,你可以使用这个方便、易读的语法:
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
在此处阅读有关 Nullable 的所有信息.
Read all about Nullable here.
这篇关于使整数为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!