检查日期值为空 - 指定的强制转换为无效

时间:2015-07-12 13:01:36

标签: sql-server vb.net datetime

我的代码有问题,我花了一天但无法找到解决方法。错误代码指定强制转换

这是非常高的机会是由于我的数据类型值检查日期值是否为null。因为当我删除I​​F ELSE语句时,代码工作正常,我可以更新数据库。

场景是我有访问时钟和时钟,所以首先访问时钟,然后信息将插入到DB而没有时钟输出时间(显然数据库中的时钟输出时间将为NULL),并且以后当访问者退出时我需要验证同一访客的时钟输出时间是否为空。

以下是我的代码:

Private Sub btn_clockout_Click(sender As Object, e As EventArgs) Handles btn_clockout.Click
    Dim con As New SqlConnection
    Dim cmd As New SqlCommand
    Dim clockouttimestatus As DateTime? = Nothing

    Try
        con.ConnectionString = "Data Source=LAPTOP-HP;Initial Catalog=COMPANY;Integrated Security=True"
        cmd.Connection = con
        con.Open()
        cmd.CommandText = "select v_clockouttime from visitor where v_id = @txt_visitorid"
        cmd.Parameters.Add("@txt_visitorid", SqlDbType.Int).Value = txt_visitorid.Text
        clockouttimestatus = cmd.ExecuteScalar()

        If IsDBNull(clockouttimestatus) Then

            cmd.CommandText = "update visitor set v_clockouttime = @lbl_displaydate where v_id = @txt_visitorid"

            cmd.Parameters.Add("@lbl_displaydate", SqlDbType.DateTime).Value = lbl_displaydate.Text
            cmd.Parameters.Add("@txt_visitorid", SqlDbType.Int).Value = txt_visitorid.Text
            cmd.ExecuteNonQuery()

            MessageBox.Show("Visitor ID is successful clockout")
        Else

            MessageBox.Show("Visitor ID is failed to clockout")

        End If

    Catch ex As Exception
        MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
    Finally
        con.Close()
    End Try

2 个答案:

答案 0 :(得分:2)

cmd.Parameters.Add("@lbl_displaydate", SqlDbType.DateTime).Value = lbl_displaydate.Text

您正在为datetime参数指定文本值。如果.NET无法将其隐式转换为日期时间,则该语句将失败。您应该在代码中处理强制转换,例如:

Dim parsedDate as DateTime 
Dim isValidDate as boolean = DateTime.TryParse(lbl_displaydate.Text, parsedDate)

If isValidDate Then
   cmd.Parameters.Add("@lbl_displaydate", SqlDbType.DateTime).Value = parsedDate
End If

答案 1 :(得分:0)

我认为当您尝试将specified cast in not valid方法的结果分配给ExecuteScalar()的变量时,会抛出Nullable(Of DateTime)错误。

Dim clockouttimestatus As DateTime? = Nothing
clockouttimestatus = cmd.ExecuteScalar()

仅当返回值为DbNull

时才会抛出此异常

在分配值

之前添加对DbNull的检查
'connection and command staff
Dim databaseValue = cmd.ExecuteScalar()
clockouttimestatus = If(IsDbNull(databaseValue) = True, Nothing, databaseValue)

If clockouttimestatus.HasValue = False Then
    'Use your update block
End If