I commonly use the SqlDataAdapter
class to retrieve data from SQL Server for consumption in a .NET application. Almost as commonly, while traversing the returned DataSet
I often hit null object exceptions because the cell contains a DbBull
which translates to Nothing
in VB.NET.
Naturally it is better to store empty cells as NULL
rather than an empty NVARCHAR
or some such data type.
What is the best practice (assuming there is one) for converting these DbNulls to an object in VB.NET. It's most commonly an empty string, but each data type has its own "most appropriate" "Empty" value?
The goal here, is that I don't want to fill my DB with garbage, nor for my application to break when it encounters a DbNull
, nor to be required to do something silly like this...
UNDESIRABLE SOLUTION!
For Each row As DataRow In dt.Rows
Dim cell1 As String = If(IsDBNull(row(0)), "", row(0).ToString)
Dim cell2 As String = If(IsDBNull(row(1)), "", row(1).ToString)
Dim cell3 As String = If(IsDBNull(row(2)), "", row(2).ToString)
Response.Write(String.Format("Cell1: {0}, Cell2: {1}, Cell3: {2}<br />", & _
{cell1, cell2, cell3})
Next
Imagine if I had 50 columns, it would be a major hassle to check all these before using them. I'd like a more intelligent solution if one exists.
Side Note:
In SQL Server it's very easy to do something similar, but not quite the same. I normally use something like isnull(@value,@value)
to ensure nulls are captured as part of my dataset.