在 vb.net 中处理 dbnull 数据 [英] handling dbnull data in vb.net

查看:25
本文介绍了在 vb.net 中处理 dbnull 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一些从 MS-Access 数据库检索并存储在 DataTable 对象/变量 myDataTable 中的数据的格式化输出.但是,myDataTable 中的某些字段包含dbNull 数据.因此,如果任何字段 lastnameintialssID 的值为 ,则以下 VB.net 代码片段将给出错误>dbNull.

I want to generate some formatted output of data retrieved from an MS-Access database and stored in a DataTable object/variable, myDataTable. However, some of the fields in myDataTable cotain dbNull data. So, the following VB.net code snippet will give errors if the value of any of the fields lastname, intials, or sID is dbNull.

   dim myDataTable as DataTable
   dim tmpStr as String
   dim sID as Integer = 1

   ...
   myDataTable = myTableAdapter.GetData() ' Reads the data from MS-Access table
   ...

   For Each myItem As DataRow In myDataTable.Rows

    tmpStr = nameItem("lastname") + " " + nameItem("initials")

    If myItem("sID")=sID Then
        ' Do something
    End If

    ' print tmpStr

   Next

那么,当字段可能包含 dbNull 时,我如何让上述代码正常工作,而不必每次都检查数据是否为 ​​dbNull,如 这个问题?

So, how do i get the above code to work when the fields may contain dbNull without having to check each time if the data is dbNull as in this question?

推荐答案

我所知道的唯一方法是测试它,但您可以进行组合以使其更容易.

The only way that i know of is to test for it, you can do a combined if though to make it easy.

If NOT IsDbNull(myItem("sID")) AndAlso myItem("sID") = sId Then
   'Do success
ELSE
   'Failure
End If

我是用 VB 编写的,因为这正是您所需要的,即使您混合了多种语言.

I wrote in VB as that is what it looks like you need, even though you mixed languages.

编辑

清理以使用 IsDbNull 使其更具可读性

Cleaned up to use IsDbNull to make it more readable

这篇关于在 vb.net 中处理 dbnull 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆