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


hi i got this error message

Private Sub DataGridView1_RowHeaderMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.RowHeaderMouseDoubleClick
        'DataGridView1.DataSource = bs

        Dim i As Integer
        i = DataGridView1.CurrentRow.Index
        txtConID.Text = DataGridView1.Item(0, i).Value
        txtLname.Text = DataGridView1.Item(1, i).Value
        PictureBox1.Image = DataGridView1.Item(2, i).Value <-here!
    End Sub

i have an image datatype i want it when i click the rowheader to be displayed on my picturebox. how can i do this?

Dani AI

Generated

Quick answer: the cell contains a byte array (System.Byte[]) coming from your database, so assigning it directly to PictureBox1.Image throws an invalid-cast. 's FromFile idea only works when the cell holds a file path string. For bytes you must convert the byte[] into a System.Drawing.Image first, handle DBNull, and dispose previous images to avoid leaks.

Try this pattern (checks for DBNull, converts bytes to an Image, clones it so the MemoryStream can be closed):

Dim val = DataGridView1.Item(2, i).Value

If val IsNot Nothing AndAlso Not IsDBNull(val) Then
    Dim bytes() As Byte = TryCast(val, Byte())
    If bytes IsNot Nothing Then
        Using ms As New System.IO.MemoryStream(bytes)
            Using tmp As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
                If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
                PictureBox1.Image = New System.Drawing.Bitmap(tmp)   'clone so stream can be closed
            End Using
        End Using
    ElseIf TypeOf val Is String Then
        If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
        PictureBox1.Image = System.Drawing.Image.FromFile(CStr(val))
    End If
Else
    PictureBox1.Image = Nothing
End If

A few tips: set PictureBox1.SizeMode = PictureBoxSizeMode.Zoom for proper scaling; load images on a background thread and Invoke the UI update if you fetch from a DB on another thread; store thumbnails or paths if you display many records to reduce memory and network load. This addresses the cast error and covers both common storage formats (byte[] vs file path).

PictureBox1.Image.FromFile(DataGridView1.Item(2, i).Value)

** .FromFile(String) - this function accepts the URL of the image in ur Drive in String

.Image() property of the picturebox accepts OBJECT and .VALUE() of the Datagrid returns a STRING. Reply to this thread for more explanations

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.