在.vb.net中将null值传递给整数变量

3

我有一个整数变量,就像这样:

Dim valetid as integer
 If cvalettype.Checked Then
            valetid = RecordID("vtid", "VType_tbl", "Vtype", cmbvalettype.Text)
        Else
            valetid = 0
        End If 

如果条件进入else语句,valetid的值将为0。这个0值会保存在数据库中。 如果条件进入else语句,我想把我的valetid保存为Null(现在在我的数据库中保存的是0)。在我的数据库中,Valetid数据类型被声明为int。我该如何做?


3
请添加将值发送到数据库的代码。当您编辑完成后,请突出显示它并点击“{}”按钮(就像我为您现有的代码所做的那样),以便将其标记为带有语法突出显示的代码。 - Damien_The_Unbeliever
2
Nullable(Of Integer) 可能是一个选项... - Tim
如果我声明了 Nullable(Of Integer),我该如何传递值? - user2674855
请查看我的帖子:http://stackoverflow.com/a/18247643/2218635 - Ramesh Rajendran
"可能重复":http://stackoverflow.com/questions/4937848/passing-in-null-integer?rq=1 - Ramesh Rajendran
3个回答

5

首先,你的整数变量在VB代码和数据库中都必须是可空的。假设数据库允许此字段为空,您可以按照以下方式操作:

Dim valetid as Integer?
If cvalettype.Checked Then
    valetid = RecordID("vtid", "VType_tbl", "Vtype", cmbvalettype.Text)
Else
    valetid = Nothing
End If

' Do stuff with your valetid variable here

或者像Neolisk更喜欢的那样:
Dim valetid as Nullable(Of Integer)
If cvalettype.Checked Then
    valetid = RecordID("vtid", "VType_tbl", "Vtype", cmbvalettype.Text)
Else
    valetid = Nothing
End If

' Do stuff with your valetid variable here

+1,虽然我更喜欢更清晰的语法Nullable(Of Integer)而不是这个令人困惑的? - Victor Zakharov
这只是语法糖。Nullable(Of Integer)或Nullable<int>是相同的东西,只是需要更多的打字。 - Douglas Barbin
没有冒犯之意 - 只是想在这里促进代码的清晰度。我的偏好是尽可能地保持代码清晰易懂,以便于那些刚开始学习VB.NET、来自旧的VB6世界甚至其他语言/框架的人理解。 - Victor Zakharov
已更新,包括备用语法。 - Douglas Barbin

0

我会;

    If cvalettype.Checked Then
        valetid = RecordID("vtid", "VType_tbl", "Vtype", cmbvalettype.Text)
    Else
        valetid = nothing
    End If 

然后稍后您可以进行测试;

    if valetid isnot nothing then
         'write valetid to database
    else
         'write dbnull to database
    end if

int 是值类型,那么你怎么能设置为 null 呢? - Ramesh Rajendran
如何将 DBNull 写入数据库 - user2674855
在我的数据库中,我应该使用什么数据类型而不是int? - user2674855
看我的回答,我已经发布了! - Ramesh Rajendran
dbnull 是 system.object 类型的。http://msdn.microsoft.com/zh-cn/library/system.dbnull.aspx - Dennis
显示剩余2条评论

-1

你的整数是否声明为可空整数? 如果是这样, 你可以简单地这样做:

Dim valetid as integer
 If cvalettype.Checked Then
            valetid = RecordID("vtid", "VType_tbl", "Vtype", cmbvalettype.Text)
        Else
            valetid.hasvalue =false
        End If 

我将valetid声明为Nullable(Of Integer),但此时显示错误:属性HasValue是只读的。 - user2674855
啊,抱歉,你可以这样分配它:valetid = nothing。 如果你不知道可空类型,请阅读这篇文章: http://msdn.microsoft.com/en-us/library/ms235245.aspx - Christian Sauer
我将valetid赋值为nothing,但是在我的数据库中仍然只得到0。 - user2674855

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接