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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With