【发布时间】:2021-09-27 20:21:14
【问题描述】:
我根据我的 SQL Server 数据库为每个按钮分配背景图像。如果一个字节为空,我会收到此错误:
无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。
我想允许没有背景图像的按钮,但错误阻止了我。
这是我的尝试:
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Imagen FROM Inventario WHERE ID=@ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
con.Close()
Else
'do nothing
End If
End Using
【问题讨论】:
-
因为你的字段在 SQL 中为 NULL,所以首先检查 NULL。
-
ID列真的是VarChar而不是Integer? -
@JoelCoehoorn 非常感谢您指出这一点。我有一个坏习惯
VarChar一切。 -
@djv 我知道它的NULL,关键是让它为NULL并且仍然能够运行程序。