How to skip null bitmap value from a database when retrieving an image

150 Views Asked by At

I am trying to set a flowlayoutpanel to show images from access database VB.net, but when it reads an empty cell from the image column is gives me error saying

specified cast is invalid

the image data is in bytes I just don't know how to properly skip a cell when there's no data. how to properly set a condition for checking null bytes?

here's my code

Private Sub loadData()
  cn.Open()
  cmd = New OleDbCommand("select [Image Name], [Item Name] from tbl_item_image", cn)

  dr = cmd.ExecuteReader
  While dr.Read
    Dim len As Long = dr.GetBytes(0, 0, Nothing, 0, 0)
    Dim array(CInt(len)) As Byte
    dr.GetBytes(0, 0, array, 0, CInt(len))

    pic = New PictureBox
    pic.Width = 100
    pic.Height = 100
    pic.BackgroundImageLayout = ImageLayout.Stretch
           
    mybtn = New Button
    mybtn.Width = 100
    mybtn.Height = 30

    AddHandler mybtn.Click, AddressOf OnButton_Click
    AddHandler mybtn.MouseHover, AddressOf OnButton_MouseHove

    Dim ms As New System.IO.MemoryStream(array)
    Dim bitmap As New System.Drawing.Bitmap(ms)

    pic.BackgroundImage = bitmap  
    mybtn.Text = dr.Item("Item Name").ToString
    FlowLayoutPanel1.Controls.Add(pic)
    pic.Controls.Add(mybtn)
  End While
  dr.Close()
  cn.Close()
End Sub

I have tried setting an If statements for checking null or empty values but I don't really know how to do it properly.

1

There are 1 best solutions below

0
najisoft On

try this

If Not Convert.IsDBNull(your image data) Then

        Dim ms As New MemoryStream(CType(your image data, Byte()))

        pic.Image = New Bitmap(Image.FromStream(ms))

        ms.Dispose()

    Else

        pic.Image = Nothing

    End If