add image to datagridview

Kim 41 Reputation points
2022-04-02T15:24:43.297+00:00

hello,

I have an app in vb.net with a database.
Now in the datagridview column "photo" I want to display an image according to the path which is in another cell "photopath".
I have the following code from an old app but I can't get it to work.

 If Me.FietsdragerBindingSource.Position > -1 Then
            For Each NRow In Me.FietsdragerDataGridViewX.Rows
                If NRow.Cells(2).Value IsNot DBNull.Value Then
                    Try
                        filenaam = (NRow.Cells(2).Value())
                        NRow.Cells(1).value() = Image.FromFile(Settings.image.Text & filenaam & ".jpg")
                    Catch ex As Exception
                        NRow.Cells(1).value() = My.Resources._error
                    End Try
                    'If fotopadTextBox.Text = Nothing Then
                    '    FotoPictureBox.Image = My.Resources._error
                    'End If
                End If
            Next
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,712 questions
0 comments No comments
{count} votes

Accepted answer
  1. LesHay 7,126 Reputation points
    2022-04-02T16:17:18.73+00:00

    Hi
    Simple example here my help. There are a couple of hard coded paths - you would need to edit accordingly if you want to try the example. You can drag the cell edges to resize.

    189442-111.png

    Option Strict On  
    Option Explicit On  
    Public Class Form1  
     Dim dt As New DataTable("Freddy")  
     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  
     With dt  
     .Columns.Add("ID", GetType(Integer))  
     .Columns.Add("Image", GetType(Image))  
     .Columns.Add("Desc", GetType(String))  
      
     .Rows.Add(123, Image.FromFile("C:\Users\lesha\Documents\VB Resources\Images\ABS.jpg"), "Some words")  
     .Rows.Add(321, Image.FromFile("C:\Users\lesha\Documents\VB Resources\Images\Amedee Lighthouse.jpg"), "More words")  
     End With  
     With DataGridView1  
     .DataSource = dt  
     .AllowUserToAddRows = False  
     End With  
     End Sub  
     Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting  
     If (e.RowIndex < 0 Or e.ColumnIndex < 0) Then Return  
      
     If DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ValueType = GetType(Image) Then  
     CType(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex),  
     DataGridViewImageCell).ImageLayout = DataGridViewImageCellLayout.Zoom  
     End If  
     End Sub  
    End Class  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.