我的代码有问题,我花了一天的时间,但无法找出一个解决方案。错误码是指定的转换为not valid
这是非常高的机会是由于我的数据类型值检查日期值是否为空。因为当我删除IF ELSE语句时,代码工作得很好,我能够更新数据库。
场景是,我有访客的时钟进入和时钟退出时间,所以首先访客时钟进入,然后信息将插入到数据库中没有时钟超时时间(显然时钟超时时间将在DB中为空),后来当访客时钟退出时,我需要验证时钟超时时间是否为空相同的访客。
下面是我的代码:
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
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
我认为当你试图将ExecuteScalar()
方法的结果分配给Nullable(Of DateTime)
的变量时,specified cast in not valid
错误将被抛出。
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