【问题标题】:check if date column in datatable is null检查数据表中的日期列是否为空
【发布时间】:2014-01-08 22:00:51
【问题描述】:
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

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

我试过了

    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.

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 你不应该使用Is Nothing而不是= Nothing吗?
    • If Not .... = Nothing 导致警告消息This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.
    • @j_t_fusion 抱歉,我已经有一段时间没有在 VB.NET 中工作了。已更正。
    猜你喜欢
    • 2017-02-20
    • 2011-11-08
    • 2021-03-08
    • 2012-11-25
    • 2020-05-18
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多