Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make An Integer Null

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
like image 276
Nick LaMarca Avatar asked Sep 02 '10 15:09

Nick LaMarca


People also ask

How do you set an integer to null?

Write a class to wrap the integer and add a boolean called “invalid“ and set it to true whenever the integer should be null. Now you can check if the integer is invalid when calling it. You could also throw an exception when getInt() gets called but “invalid“ is true.

Can a integer be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

Can you add NULL to an int?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);

Can you set an integer to null in C?

In c, besides pointers you cannot set c objects to NULL.


1 Answers

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.

like image 124
Larsenal Avatar answered Oct 18 '22 08:10

Larsenal