Sql 尝试将DBNull转换为日期,但迄今为止没有任何运气。

Sql 尝试将DBNull转换为日期,但迄今为止没有任何运气。,sql,vb.net,dbnull,Sql,Vb.net,Dbnull,我使用另一个填充的txtbox(汽车注册)作为过滤器,从sql数据库将一个值加载到txtbox(驱动程序)中 这样我就能为那辆车找到合适的司机了。由于每辆车都可能有很多人在其行驶时间内驾驶,因此我使用IIf条款来确保选择了当前的驾驶员 我得到这个错误: 未为类型“DBNull”和类型“Date”定义运算符“>”。 我知道我需要将DBNull转换为日期格式,但我很难做到这一点,我已经尝试了一些方法,到目前为止,我已经做到了这一点 Dim cdriver As New Dic

我使用另一个填充的txtbox(汽车注册)作为过滤器,从sql数据库将一个值加载到txtbox(驱动程序)中

这样我就能为那辆车找到合适的司机了。由于每辆车都可能有很多人在其行驶时间内驾驶,因此我使用IIf条款来确保选择了当前的驾驶员

我得到这个错误:

未为类型“DBNull”和类型“Date”定义运算符“>”。

我知道我需要将DBNull转换为日期格式,但我很难做到这一点,我已经尝试了一些方法,到目前为止,我已经做到了这一点

            Dim cdriver As New Dictionary(Of String, Object)

        cdriver.Add("Registration", txtreg.Text)

        Dim currentdriver As DataTable

        currentdriver = BusinessData.VerifierLogic.Load("[Car History]", cdriver)

        Dim currentdrivername As String = ""
        Dim currentenddate As DateTime

        For Each row As DataRow In currentdriver.Rows
            If DateDiff(DateInterval.Day, row("end_date"), DateTime.Now) > 0 Then
                currentdrivername = row("driver_name")
                currentenddate = row("end_date")

                IIf(row("end_date") Is DBNull, "1 jan 1900", row("end_date"))
            End If
        Next

        txtdriver.Text = currentdrivername
    Catch ex As Exception

        MsgBox(ex.Message)

    End Try
任何帮助都将不胜感激

Paul

那么
行(“结束日期”)
可以为空吗?您可以使用
DataRow
-扩展方法
字段
,它支持可为空的类型,并且是强类型的:

For Each row As DataRow In currentdriver.Rows
    Dim endDate As Date? = row.Field(Of Date?)("end_date")
    If endDate.HasValue AndAlso endDate.Value > Date.Now Then
       currentdrivername = row.Field(Of String)("driver_name")
       currentenddate = endDate.Value
       Exit For ' otherwise you are overwriting these variables always '
    End If
Next

必须感谢蒂姆·施梅尔特的帮助

我不得不稍微改变一些东西来让它运行,但代码的核心是你的。以下是完成的文章:

            For Each row As DataRow In currentdriver.Rows
            Dim endDate As Date? = row.Field(Of Date?)("end_date")
            If Not endDate.HasValue Then
                currentdrivername = row.Field(Of String)("driver_name")
            ElseIf endDate.Value > Date.Now Then
                currentdrivername = row.Field(Of String)("driver_name")
            End If

IIf(row.IsNull(“end_date”),“1900年1月1日”,row(“end_date”))IIf只是其中的一个表达式,而不是仍然带来相同问题的声明。