Sky Scraper Sky Scraper - 6 months ago 75
SQL Question

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

when i try to select an item in the ListView that has no image in my database this error shows

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
i tried to put up some code like
isDBNull
or
DBNull
but it's applicable.

here's my code:

Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
Dim Sql As String = "select * from candidate where idn='" & LvPeople.SelectedItems(0).Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
End If
End Sub
End Class


the error points here:

Dim imagebytes As Byte() = CType(dr("photo"), Byte())


i really have no idea what to put here. just a newbie here.

Answer

Since it is possible that there is no image data previously saved for a row, you need to test for DBNull before trying to use it:

If IsDBNull(dr("photo")) = False Then
    Dim imagebytes As Byte() = CType(dr("photo"), Byte())
    Using ms As New IO.MemoryStream(imagebytes)
        PictureBox1.Image = Image.FromStream(ms)
        PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
    End Using
Else
      ' maybe display a "no Photo Available" stock image
End If

Note that this DBNull test is different than the one Steve is using. IsDBNull is a language function while the one he is using is a method of the DataReader object, which is also why there are different requirements. Yet a third way would be to compare it to System.DbNull:

If DBNull.Value.Equals(dr("photo")) = False Then
    ...
End If
Comments