VB.NET - Code Samples - FixNull

VB.NET FixNull Function


Handle Database Null Values in VB.NET

The Problem:

When returning values back from a datareader I often have troubles reading and converting dbnull values. This function handles the null values and returns the default variable values for several variable types.

The Code:

    Public Shared Function FixNull(ByVal objData As Object, ByVal objType As Type) As Object
        If IsDBNull(objData) Then
            Select Case System.Type.GetTypeCode(objType)
                Case TypeCode.Int16, TypeCode.Int32, TypeCode.Int64, _
                    TypeCode.Decimal, TypeCode.Double, _
                    TypeCode.Single, TypeCode.UInt16, TypeCode.UInt32, _
                    Return 0
                Case TypeCode.String
                    Return ""
                Case TypeCode.DateTime
                    Return DateTime.MinValue
                Case TypeCode.Boolean
                    Return False
            End Select
            Return objData
        End If
    End Function

    *Example usage:
     Dim itemCount as int32 = fixnull(somevalue,gettype(int32))
About this page: