Click here to Skip to main content
15,904,638 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi Everyone

I am working on a project where I have a list of images displayed through datagridview.
I want to load an image into picturebox when the particular image is clicked in datagridview.

My code
VB
Private Sub DataGridView1_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
       sql.Open()

       cmd = New SqlCommand("select pic from detail4 where id='" & DataGridView1.CurrentRow.Cells(0).Value() & "'", sql)
       Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
       If Not imageData Is Nothing Then
           Using ms As New MemoryStream(imageData, 0, imageData.Length)
               ms.Write(imageData, 0, imageData.Length)
               PictureBox1.BackgroundImage = Image.FromStream(ms, True)
           End Using
       End If

   End Sub


I get Out of memory exception..
What may be the problem.
Posted

1 solution

Hello !

Working like charm !

VB
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        Dim pCell As New DataGridViewImageCell

        pCell = Me.DataGridView1.Item("ThumbNailPhotoDataGridViewImageColumn", e.RowIndex)
        Me.PictureBox1.Image = byteArrayToImage(pCell.Value)
    End Sub
    Private Function byteArrayToImage(ByVal byt As Byte()) As Image

        Dim ms As New System.IO.MemoryStream()
        Dim drwimg As Image = Nothing

        Try
            ms.Write(byt, 0, byt.Length)
            drwimg = New Bitmap(ms)
        Finally
            ms.Close()
        End Try

        Return drwimg

    End Function
 
Share this answer
 
v2
Comments
Tyoub 10-Aug-16 2:34am    
Thanks a lot. Very effective function

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900