当我尝试在ListView中选择一个在数据库中没有图像的项目时,此错误显示Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.,我尝试放置某些代码,例如isDBNullDBNull,但它适用。

这是我的代码:

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


错误点在这里:

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

我真的不知道该放在哪里。这里只是一个新手。

最佳答案

由于可能以前没有为行保存任何图像数据,因此需要在尝试使用DBNull之前对其进行测试:



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


请注意,此DBNull测试与Steve使用的测试不同。 IsDBNull是一种语言功能,而他正在使用的语言功能是DataReader对象的方法,这也是为什么存在不同要求的原因。第三种方法是将其与System.DbNull进行比较:

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

关于mysql - 无法将类型为“System.DBNull”的对象转换为类型为“System.Byte []”的对象。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26369228/

10-11 07:58