Passing in NULL integer?

2019-08-03 18:26发布

问题:

I have a function that takes in a number of parameters.. it then does a db insert.

i have a foreign key on one of the fields (modelID)

i want to pass a NULL if no model ID is selected.

i tried the following:

 Dim model As Nullable(Of Integer)
        If ddlModel.SelectedValue = "Other" Then
            'add new model
            model = cSource.InsertModel(txtModel.Text, ddlManuf.SelectedValue)
        ElseIf ddlModel.SelectedValue = "0" Then
            model = Nothing
        Else
            model = ddlModel.SelectedValue
        End If

but now i get an error saying: Nullable object must have a value.

how can i fix this? if i pass in a 0, it does not insert because it breaks the DB constraints :(

回答1:

Use "model = DBNull.Value"



回答2:

Do instead:

model.Value = Nothing

and let us know if the error still happens?

As well, when you have an empty date you can pass DBNull.Value to the db.



回答3:

the following worked:

 Dim model As Integer
        If ddlModel.SelectedValue = "Other" Then
            'add new model
            model = cSource.InsertModel(txtModel.Text, ddlManuf.SelectedValue)
        ElseIf ddlModel.SelectedValue = "0" Then
            model = Nothing
        Else
            model = ddlModel.SelectedValue
        End If

i then do a check for 0 when adding a parameter to the stored procedure, and if it's 0, then i assign DBnull to it.