如何检查字节是否为空vb.net



我根据我的SQL Server数据库分配背景图像给每个按钮。如果一个字节是空的,我得到这个错误:

无法强制转换'System '类型的对象。

DBNull' to type '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
Dim ItemID As Integer = 1
Dim sql As String = "SELECT Imagen FROM Inventario WHERE ID=@ID"
Using con As New SqlConnection("constring"), _
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("@ID", SqlDbType.Integer).Value = ItemID
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(myreader("Imagen"), Byte())         
Using ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End Using
End If
End Using
End Using

基于c#的答案,转换为vb.net并添加NULL检查

Using con As New SqlConnection("constring")
Using cmd = con.CreateCommand()
cmd.CommandText = "SELECT Imagen FROM Inventario WHERE ID=@ID"
Dim ItemID = 1
cmd.Parameters.AddWithValue("@ID", ItemID)
con.Open()
Dim res = cmd.ExecuteScalar()
If res IsNot Nothing Then
ImgSql = CType(res, Byte())
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End If
End If
End Using
End Using

相关内容

  • 没有找到相关文章

最新更新