检查datatable中的date列是否为null

时间:2014-01-08 22:00:51

标签: asp.net vb.net date datatable dbnull

Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As DataTable = New DataTable()
dt.Load(dr)

For Each row As DataRow In dt.Rows

    Dim dob_str As String = ""

    'code to check if row.Field(Of Date)("DOB") is dbnull
    'if not dbnull then dob_str = row.Field(Of Date)("DOB")

Next

如何检查Date中每行的DataTable类型列是否为空?

我试过

    If Not row.Field(Of Date)("DOB") = Nothing Then
        dob_str = row.Field(Of Date)("DOB")
    End If

    Dim nullCheck As Boolean = IsDBNull(row.Field(Of Date)("DOB"))
    If nullCheck = False Then
        dob_str = row.Field(Of Date)("DOB")
    End If

但它们都在运行时产生了Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type.

1 个答案:

答案 0 :(得分:1)

使用Nullable类型

If row.Field(Of Date?)("DOB") IsNot Nothing Then
    dob_str = row.Field(Of Date)("DOB")
End If

或者

If row.Field(Of Date?)("DOB").HasValue Then
    dob_str = row.Field(Of Date)("DOB")
End If

或使用IsNull

If Not row.IsNull("DOB") Then
    dob_str = row.Field(Of Date)("DOB")
End If