How to check if DataReader value is not null?

前端 未结 3 1643
忘掉有多难
忘掉有多难 2020-12-02 00:57

I\'m writing a VB.Net code that reads an Oracle Table through an SQL query.

The SQL query may return some null columns. I\'m trying to check if these columns are nul

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 01:39

    Using Generic function with extension, will make it easier.

    Imports System.Runtime.CompilerServices
    
    
    Public Module DataReaderExtensions
      Public Function GetValue(Of T)(ByVal drVar As Object) As T
        If drVar.Equals(DBNull.Value) Then
            ' Value is null, determine the return type for a default
            If GetType(T).Equals(GetType(String)) Then
                Return CType(CType("", Object), T)
            Else
                ' If it's anything else just return nothing
                Return CType(Nothing, T)
            End If
        Else
            ' Cast the value into the correct return type
            Return CType(drVar, T)
        End If
      End Function
    End Module
    

    And you can call it like

    dr.Item("abc").GetValue(string)
    dr.Item("def").GetValue(Nullable(of Date))
    

提交回复
热议问题