Question

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

How do I check if the Date type column for each row in the DataTable is empty?

I tried

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

and

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

but they all resulted in the Cannot cast DBNull.Value to type 'System.DateTime'. Please use a nullable type. during runtime.

Was it helpful?

Solution

Use a Nullable type

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

Or

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

Or use IsNull

If Not row.IsNull("DOB") Then
    dob_str = row.Field(Of Date)("DOB")
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top