Make An Integer Null

▼魔方 西西 提交于 2019-12-08 14:50:51

问题


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

回答1:


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.




回答2:


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



回答3:


My application uses a lot of labels that start out blank (Text property), but need to be incremented as integers, so I made this handy function:

    Public Shared Function Nullinator(ByVal CheckVal As String) As Integer
    ' Receives a string and returns an integer (zero if Null or Empty or original value)
    If String.IsNullOrEmpty(CheckVal) Then
        Return 0
    Else
        Return CheckVal
    End If
End Function

This is typical example of how it would be used:

Dim Match_Innings As Integer = Nullinator(Me.TotalInnings.Text)

Enjoy!




回答4:


_intDLocation = Nothing


来源:https://stackoverflow.com/questions/3628757/make-an-integer-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!