Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling dbnull data in vb.net

Tags:

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 

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?

like image 952
Azim J Avatar asked Oct 21 '08 18:10

Azim J


People also ask

What is DBNull in VB net?

DBNull value indicates that the Object represents missing or nonexistent data. DBNull is not the same as Nothing , which indicates that a variable has not yet been initialized. DBNull is also not the same as a zero-length string ( "" ), which is sometimes referred to as a null string.

How assign DBNull value to string in VB net?

The alternative is to use the Nullable(Of String) type for your variable. This special type allows you to assign DbNull to it directly and then ask it if it is null through the HasValue property. You will still need to write the DbNull value manually since you can never convert a nullable type to DbNull.

How do you use DBNull value?

If a database field has missing data, you can use the DBNull. Value property to explicitly assign a DBNull object value to the field. However, most data providers do this automatically. To evaluate database fields to determine whether their values are DBNull, you can pass the field value to the DBNull.

What is DBNull value?

The DBNull class represents a nonexistent value. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.


1 Answers

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 

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

Edit

Cleaned up to use IsDbNull to make it more readable

like image 94
Mitchel Sellers Avatar answered Sep 19 '22 15:09

Mitchel Sellers