Home > Software design >  How to check if byte is null vb.net
How to check if byte is null vb.net

Time:09-28

I'm assigning background images to every button according to my SQL Server database. If a byte is null I get this error:

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

I want to allow buttons with no background images, but the error is preventing me.

Here is what I attempted:

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

CodePudding user response:

Based on this answer in C#, converted to vb.net and added NULL check

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

CodePudding user response:

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
  • Related