views:

43

answers:

1

I tend to use

If Not IsDBNull(dr("data")) Then
     myData = dr("data")
End If

to catch nulls. Is there a better way? It seems I use this over and over again? Anyone write a function to check this something like

mydata = IfNotNull("data")

I don't know how to handle the different data types that could be returned. Thanks for any thoughts!

+1  A: 

In cases where my CLR object is Nullable, back when I was using VB.NET I used this extension method:

    Private Function GetNullable(Of T As Structure)(ByVal row As System.Data.DataRow, ByVal fieldname As String, ByVal convert As Conversion(Of T)) As Nullable(Of T)
        Dim nullable As Nullable(Of T)
        If System.Convert.IsDBNull(row(fieldname)) Then
            nullable = Nothing
        Else
            nullable = convert(row, fieldname)
        End If
        Return nullable
    End Function

With the following delegate for Conversion(Of T):

Private Delegate Function Conversion(Of T)(ByVal row As System.Data.DataRow, ByVal fieldname As String) As T

I then layer on extensions for relevant datatypes:

    <Extension()> _
    Public Function GetDouble(ByVal row As System.Data.DataRow, ByVal name As String) As Double
        Return Convert.ToDouble(row(name))
    End Function

    <Extension()> _
    Public Function GetNullableDouble(ByVal row As System.Data.DataRow, ByVal name As String) As System.Nullable(Of Double)
        Return GetNullable(Of Double)(row, name, AddressOf GetDouble)
    End Function

Finally, I can use:

Dim amount As Double? = dr.GetNullableDouble("amount")
Larsenal
Awesome! that is exactly what I needed! And introduced me to a few new concepts to wrap my brain around! Thanks indeed!
mellerbeck
Ok, one question. I haven't been able to use this with DR.GetNullableDouble ? is that because it should extend sqlclient.sqldatareader ??
mellerbeck
Yes, I should have provided an example that extends sqldatareader for this example. I'll edit when I have time.
Larsenal
You should take a look at this article: http://www.codeproject.com/KB/database/NullableReaders.aspx
Larsenal
Great NullableReader works well! I am still interested in seeing the extension of the sqldatareader. It opened my eyes to the wonders of extensions! Always more to learn!
mellerbeck