我在运行程序时没有数据/值获取时遇到问题,出现以下错误:


  无法将对象从DBNull强制转换为其他类型。


我尝试使用if dr.hasrow()对其进行验证,但仍然出现错误。

drqry = "SELECT max(num) FROM tbCVinfo WHERE cvno LIKE '%" & cvstr & "%'"

cmd2.CommandText = drqry
cmd2.Connection = con

Dim result As String = ""

cv = Convert.ToInt32(cmd2.ExecuteScalar())
'''''''''in this section I'm getting the error.

cv = cv + 1
If cv >= 0 And cv <= 9 Then
  ...............
Else
    cn = "0001"
End If
cn = result

cvno = cn

最佳答案

解决此问题的一种简单方法是检查返回的值是否为DBNull

Dim cv As Integer
Dim queryResult = cmd2.ExecuteScalar()
If IsDBNull(queryResult) Then
    ' No matching records. Do something about it.
Else
    cv = DirectCast(queryResult, Integer)
End If

09-30 17:05
查看更多