locked
How to add an image to datagridview rows depending on its gender RRS feed

  • Question

  • Hi guys,

    I have a datagridview containing records including gender. I want to add a column for image (as first column). When i load student data from database to datagridview, i want to filter that records by its gender (if row data gender is male it will add male icon to image column from imagelist, and add female icon if the row gender is female).

    How can I do that?

    Here's the link of my project, maybe you can help me:

    https://github.com/zirj0hn/vbdotnetprojects/blob/master/vbdotnetColumnProperties.rar

    Thanks in advance!

    Thursday, May 31, 2018 12:22 AM

Answers

  • Hi guys,

    I have a datagridview containing records including gender. I want to add a column for image (as first column). When i load student data from database to datagridview, i want to filter that records by its gender (if row data gender is male it will add male icon to image column from imagelist, and add female icon if the row gender is female).

    Hi zirjohn,

    According to your description, you just want to add different image based on gender in datagridviewimagecolumn, you can take a look the following code.

     Private Sub Frmdatagridview_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            
            Dim dt As New DataTable
            dt.Columns.Add("Id", GetType(Integer))
            dt.Columns.Add("Studengname", GetType(String))
            dt.Columns.Add("Gender", GetType(String))
    
            dt.Rows.Add(1, "A", "Male")
            dt.Rows.Add(2, "B", "Female")
            dt.Rows.Add(3, "C", "Male")
            dt.Rows.Add(4, "D", "Female")
            dt.Rows.Add(5, "E", "Male")
            dt.Rows.Add(6, "F", "Female")
            dt.Rows.Add(7, "G", "Male")
            DataGridView1.DataSource = dt
            Dim img As New DataGridViewImageColumn
            img.Name = "Image"
            DataGridView1.Columns.Add(img)
    
            AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting
        End Sub
     Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
            If e.RowIndex > -1 AndAlso e.ColumnIndex = Me.DataGridView1.Columns("Image").Index Then
    
                If Me.DataGridView1("Gender", e.RowIndex).Value IsNot Nothing Then
                    Dim s As String = Me.DataGridView1("Gender", e.RowIndex).Value.ToString()
    
                    Select Case s
                        Case "Female"
                            e.Value = Image.FromFile("D:\Image\1.jpg")
                        Case "Male"
                            e.Value = Image.FromFile("D:\Image\2.jpg")
                    End Select
                End If
            End If
        End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by Cor Ligthert Thursday, May 31, 2018 10:59 AM
    • Marked as answer by zirj0hn Friday, June 1, 2018 12:24 AM
    Thursday, May 31, 2018 5:58 AM

All replies

  • Hello,

    Have not looked at your project. What I suggest is the having a reference table for gender which has a primary key (a foreign key for the main table), a string field for gender e.g. Male, Female and a field for the image to associate with the gender.

    Schema for demo purposes

    Your SELECT statement using tables above would look like this where @Gender is the gender type, here 2 is male, 1 is female.

    SELECT P.id, P.FirstName, P.LastName, G.Gender, G.GenderIdentifier, G.GenderImage FROM Persons1 AS P INNER JOIN GenderTypes AS G ON P.GenderIdentifier = G.GenderIdentifier WHERE G.GenderIdentifier = @Gender

    You would first write the SELECT statement above out of code, in a .SQL file in Visual Studio or SQL-Server Management Studio (if this is MS-Access write it in a new query window).

    Here is how I would test the SELECT statement where the DECLARE becomes a parameter for your commandText of the command object.

    DECLARE @Gender INT  = 2;
    SELECT  P.id ,
            P.FirstName ,
            P.LastName ,
            G.Gender ,
            G.GenderIdentifier ,
            G.GenderImage
    FROM    Persons1 AS P
            INNER JOIN GenderTypes AS G ON P.GenderIdentifier = G.GenderIdentifier
    WHERE   G.GenderIdentifier = @Gender;

    Here I have a image field but not populated

    Read the data into a DataTable and present it to the DataSource of the DataGridView.

    If you want all records at once with no where condition then later filter for one gender this can be done using the DataView of the DataTable RowFiilter method or Filter method of a BindingSource that has the above DataTable as it's DataSource.

    Using a TableAdapter? It's possible but will get a tad nasty as when using more than one table in a query such as the above you are violating the classes generated for you and must be careful with the output.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, May 31, 2018 12:48 AM
  • Hi

    Here is some bare bones code to illustrate one way to do it. I have used 2 images which I had handy, you will have your own. In this example,column 1 holds gender (Male/Female) which is used to choose image to display.

    ' Form1 with:
    ' DataGridView1 (4 default columns)
    Option Strict On
    Option Explicit On
    Public Class Form1
      ' path to Images directory 
      Dim path As String = "C:\Users\lesha\Desktop\SavedIcons"
      Dim im As New ImageList
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With im
          ' add 2 Images (here I just 
          ' used Yes and No whichI had
          ' handy
          .ImageSize = New Size(32, 32)
          .Images.Add("M", Image.FromFile(IO.Path.Combine(path, "No.ico")))
          .Images.Add("F", Image.FromFile(IO.Path.Combine(path, "Yes.ico")))
        End With
        With DataGridView1
          .Rows.Add(Nothing, "Male", "Some", 33)
          .Rows.Add(Nothing, "Female", "Random", 55)
          .Rows.Add(Nothing, "Female", "Stuff", 77)
          .Rows.Add(Nothing, "Male", "for example", 66)
        End With
        AddImages()
      End Sub
      Sub AddImages()
        For Each r As DataGridViewRow In DataGridView1.Rows
          With r
            If Not .Index = DataGridView1.NewRowIndex Then
              Select Case .Cells(1).Value.ToString.ToLower
                Case "male"
                  .Cells(0).Value = im.Images(0)
                Case Else
                  .Cells(0).Value = im.Images(1)
              End Select
            End If
          End With
        Next
      End Sub
      Private Sub DataGridView1_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowValidated
        AddImages()
      End Sub
    End Class
    


    Regards Les, Livingston, Scotland

    Thursday, May 31, 2018 1:27 AM
  • Hi

    Here is some bare bones code to illustrate one way to do it. I have used 2 images which I had handy, you will have your own. In this example,column 1 holds gender (Male/Female) which is used to choose image to display.

    ' Form1 with:
    ' DataGridView1 (4 default columns)
    Option Strict On
    Option Explicit On
    Public Class Form1
      ' path to Images directory 
      Dim path As String = "C:\Users\lesha\Desktop\SavedIcons"
      Dim im As New ImageList
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With im
          ' add 2 Images (here I just 
          ' used Yes and No whichI had
          ' handy
          .ImageSize = New Size(32, 32)
          .Images.Add("M", Image.FromFile(IO.Path.Combine(path, "No.ico")))
          .Images.Add("F", Image.FromFile(IO.Path.Combine(path, "Yes.ico")))
        End With
        With DataGridView1
          .Rows.Add(Nothing, "Male", "Some", 33)
          .Rows.Add(Nothing, "Female", "Random", 55)
          .Rows.Add(Nothing, "Female", "Stuff", 77)
          .Rows.Add(Nothing, "Male", "for example", 66)
        End With
        AddImages()
      End Sub
      Sub AddImages()
        For Each r As DataGridViewRow In DataGridView1.Rows
          With r
            If Not .Index = DataGridView1.NewRowIndex Then
              Select Case .Cells(1).Value.ToString.ToLower
                Case "male"
                  .Cells(0).Value = im.Images(0)
                Case Else
                  .Cells(0).Value = im.Images(1)
              End Select
            End If
          End With
        Next
      End Sub
      Private Sub DataGridView1_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowValidated
        AddImages()
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    This is working, but this making the program slow since after loading data to table it will be filtered again every row for loading gender image. So this not the answer specially when handling huge data on the datagridview.
    • Edited by zirj0hn Thursday, May 31, 2018 5:29 AM Edited.
    Thursday, May 31, 2018 5:28 AM
  • Hi guys,

    I have a datagridview containing records including gender. I want to add a column for image (as first column). When i load student data from database to datagridview, i want to filter that records by its gender (if row data gender is male it will add male icon to image column from imagelist, and add female icon if the row gender is female).

    Hi zirjohn,

    According to your description, you just want to add different image based on gender in datagridviewimagecolumn, you can take a look the following code.

     Private Sub Frmdatagridview_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            
            Dim dt As New DataTable
            dt.Columns.Add("Id", GetType(Integer))
            dt.Columns.Add("Studengname", GetType(String))
            dt.Columns.Add("Gender", GetType(String))
    
            dt.Rows.Add(1, "A", "Male")
            dt.Rows.Add(2, "B", "Female")
            dt.Rows.Add(3, "C", "Male")
            dt.Rows.Add(4, "D", "Female")
            dt.Rows.Add(5, "E", "Male")
            dt.Rows.Add(6, "F", "Female")
            dt.Rows.Add(7, "G", "Male")
            DataGridView1.DataSource = dt
            Dim img As New DataGridViewImageColumn
            img.Name = "Image"
            DataGridView1.Columns.Add(img)
    
            AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting
        End Sub
     Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
            If e.RowIndex > -1 AndAlso e.ColumnIndex = Me.DataGridView1.Columns("Image").Index Then
    
                If Me.DataGridView1("Gender", e.RowIndex).Value IsNot Nothing Then
                    Dim s As String = Me.DataGridView1("Gender", e.RowIndex).Value.ToString()
    
                    Select Case s
                        Case "Female"
                            e.Value = Image.FromFile("D:\Image\1.jpg")
                        Case "Male"
                            e.Value = Image.FromFile("D:\Image\2.jpg")
                    End Select
                End If
            End If
        End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Proposed as answer by Cor Ligthert Thursday, May 31, 2018 10:59 AM
    • Marked as answer by zirj0hn Friday, June 1, 2018 12:24 AM
    Thursday, May 31, 2018 5:58 AM
  • You could use a font. I think this webdings comes with windows and then there are others too if you hunt you can find better ones. You can also use colors ie blue pink etc. This will give the fastest rendering times.

    I suspect when your's is slow from Leshay's example that could be optimized (show your code)??

    Public Class Form6
    
        Private WithEvents dgv As New DataGridView
    
        Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Controls.Add(dgv)
            dgv.Dock = DockStyle.Fill
    
            dgv.RowTemplate.Height = 50
            dgv.RowTemplate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft
            dgv.ColumnCount = 2
            dgv.Columns(0).Name = "ID"
            dgv.Columns(1).Name = "Name"
            dgv.Rows.Add({Chr(128), "Billy"})
            dgv.Rows.Add({Chr(129), "Sue"})
            dgv.Columns(0).DefaultCellStyle.Font = New Font("Webdings", 36, FontStyle.Regular)
            dgv.Columns(0).DefaultCellStyle.ForeColor = Color.Blue
    
        End Sub
    End Class

    Thursday, May 31, 2018 9:46 AM
  • Cherry,

    Nice, I would make some slight changes in your case to prevent images should be in a folder. Also the row height needs to be set I saw

            DataGridView1.AllowUserToAddRows = False
        End Sub
        Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
            If e.RowIndex > -1 AndAlso e.ColumnIndex = Me.DataGridView1.Columns("Image").Index Then
    
                If Me.DataGridView1("Gender", e.RowIndex).Value IsNot Nothing Then
                    Dim s As String = Me.DataGridView1("Gender", e.RowIndex).Value.ToString()
    
                    Select Case s
                        Case "Female"
                            e.Value = My.Resources.M
                        Case "Male"
                            e.Value = My.Resources.F
                        Case Else
                            e.Value = My.Resources.N
                    End Select
                End If
            End If
        End Sub
        Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
            DataGridView1.Rows(e.RowIndex).Height = 42
        End Sub


    Success
    Cor

    • Marked as answer by zirj0hn Friday, June 1, 2018 12:21 AM
    • Unmarked as answer by zirj0hn Friday, June 1, 2018 12:25 AM
    • Marked as answer by zirj0hn Friday, June 1, 2018 12:25 AM
    • Unmarked as answer by zirj0hn Friday, June 1, 2018 12:25 AM
    Thursday, May 31, 2018 10:59 AM
  • Hi Tommy,

    Very clever. I did not propose it as answer, simply because the code from Cherry is more based on this what the OP wrote: "When i load student data from database to datagridview, i want to filter that records by its gender"

    But I find your code very clever. 

    (By the way, I think that clever part can also be implemented in the code of cherry.)

    :-) 


    Success
    Cor



    Thursday, May 31, 2018 11:26 AM
  • Hi Tommy,

    Very clever. I did not propose it as answer, simply because the code from Cherry is more based on this what the OP wrote: "When i load student data from database to datagridview, i want to filter that records by its gender"

    But I find your code very clever. 

    (By the way, I think that clever part can also be implemented in the code of cherry.)

    :-) 


    Success
    Cor



    Thanks Cor.

    Yes you can implement a font method several ways.

    Plus, notice in the example the data itself has is value ie chr(128) so no conversion or  "filter" is needed.

    Of course you have to deal with those chrs as data when the data is first entered to the db but that is require with any method. Or you could use anything and filter it later.

    And I supose there are other gotchas with a font.

    However I am sure it will be fast to draw if using a font. :)

    PS Cherry, 

    As Cor mentions one should not read from disc repeatedly in a cell event. I also suspect it will give out of memory errors and or file in use errors etc.

    Thursday, May 31, 2018 11:39 AM
  • Okay, had sometime to put together a code sample using the schema I presented in my first reply.

    Source code includes a script to create the database and populate both tables.

    Note, the idea of storing images in a table rather in the application is a) no need to recompile the app if the images change b) we are already reading data so why not read the images rather than have an additional process to load the images.

    Note I set the tag property of each RadioButton according to the gender role which is shown when looking at the radio button properties.

    Here is a screenshot where the RadioButton controls permit filtering.

    Data in SQL-Server

    Form with all code. Nothing configured for the DataGridView other then row height set to 33.

    Imports System.Data.SqlClient
    
    Public Class Form1
        '
        ' The BindingSource is optional but provides
        ' easy access to the current row data along
        ' with the entire DataTable if needed.
        '
        Private _bs As New BindingSource
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            Dim ops As New DataOperations
            _bs.DataSource = ops.Read
            DataGridView1.DataSource = _bs
            DataGridView1.Columns("FirstName").HeaderText = "First"
            DataGridView1.Columns("LastName").HeaderText = "Last"
            DataGridView1.Columns("GenderImage").HeaderText = "Gender"
        End Sub
        ''' <summary>
        ''' Filter based on selected radio button where the All tag is 0
        ''' and male is 2, female 1
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub cmdFilter_Click(sender As Object, e As EventArgs) Handles cmdFilter.Click
            Dim genderId As Integer = CInt(
                Panel1.Controls.OfType(Of RadioButton).
                    FirstOrDefault(Function(r) r.Checked).Tag)
    
            If genderId = 0 Then
                _bs.Filter = ""
            Else
                _bs.Filter = $"GenderIdentifier = {genderId}"
            End If
        End Sub
    End Class
    Public Class DataOperations
        ''' <summary>
        ''' Read from two table via a join where 
        ''' Persons1 has names and a key into the
        ''' second table GenderTypes
        ''' 
        ''' We hide the id column
        ''' </summary>
        ''' <returns></returns>
        Public Function Read() As DataTable
            Dim dt As New DataTable
            Dim ConnectionString As String =
                    "Data Source=KARENS-PC;Initial Catalog=People1;Integrated Security=True"
    
            Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
                Using cmd As New SqlCommand With {.Connection = cn}
                    cmd.CommandText =
                        <SQL>
                        SELECT  P.id ,
                                P.FirstName ,
                                P.LastName ,
                                G.GenderIdentifier,
                                G.GenderImage
                        FROM    Persons1 AS P
                                INNER JOIN GenderTypes AS G ON P.GenderIdentifier = G.GenderIdentifier
                        </SQL>.Value
    
                    cn.Open()
    
                    ' load data
                    dt.Load(cmd.ExecuteReader())
    
                    ' hide identifier
                    dt.Columns("id").ColumnMapping = MappingType.Hidden
                    ' hide seconary identifier which is needed for filtering
                    dt.Columns("GenderIdentifier").ColumnMapping = MappingType.Hidden
                End Using
            End Using
    
            Return dt
        End Function
    
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Thursday, May 31, 2018 12:35 PM
  • Cherry,

    Nice, I would make some slight changes in your case to prevent images should be in a folder. Also the row height needs to be set I saw

            DataGridView1.AllowUserToAddRows = False
        End Sub
        Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
            If e.RowIndex > -1 AndAlso e.ColumnIndex = Me.DataGridView1.Columns("Image").Index Then
    
                If Me.DataGridView1("Gender", e.RowIndex).Value IsNot Nothing Then
                    Dim s As String = Me.DataGridView1("Gender", e.RowIndex).Value.ToString()
    
                    Select Case s
                        Case "Female"
                            e.Value = My.Resources.M
                        Case "Male"
                            e.Value = My.Resources.F
                        Case Else
                            e.Value = My.Resources.N
                    End Select
                End If
            End If
        End Sub
        Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
            DataGridView1.Rows(e.RowIndex).Height = 42
        End Sub


    Success
    Cor

    Hi This one is simply but a working code. This meets my requirements. I just used image from imageslist rather than using resources. Thank you very much!
    Friday, June 1, 2018 12:21 AM
  • Okay, had sometime to put together a code sample using the schema I presented in my first reply.

    Source code includes a script to create the database and populate both tables.

    Note, the idea of storing images in a table rather in the application is a) no need to recompile the app if the images change b) we are already reading data so why not read the images rather than have an additional process to load the images.

    Note I set the tag property of each RadioButton according to the gender role which is shown when looking at the radio button properties.

    Here is a screenshot where the RadioButton controls permit filtering.

    Data in SQL-Server

    Form with all code. Nothing configured for the DataGridView other then row height set to 33.

    Imports System.Data.SqlClient
    
    Public Class Form1
        '
        ' The BindingSource is optional but provides
        ' easy access to the current row data along
        ' with the entire DataTable if needed.
        '
        Private _bs As New BindingSource
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            Dim ops As New DataOperations
            _bs.DataSource = ops.Read
            DataGridView1.DataSource = _bs
            DataGridView1.Columns("FirstName").HeaderText = "First"
            DataGridView1.Columns("LastName").HeaderText = "Last"
            DataGridView1.Columns("GenderImage").HeaderText = "Gender"
        End Sub
        ''' <summary>
        ''' Filter based on selected radio button where the All tag is 0
        ''' and male is 2, female 1
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        Private Sub cmdFilter_Click(sender As Object, e As EventArgs) Handles cmdFilter.Click
            Dim genderId As Integer = CInt(
                Panel1.Controls.OfType(Of RadioButton).
                    FirstOrDefault(Function(r) r.Checked).Tag)
    
            If genderId = 0 Then
                _bs.Filter = ""
            Else
                _bs.Filter = $"GenderIdentifier = {genderId}"
            End If
        End Sub
    End Class
    Public Class DataOperations
        ''' <summary>
        ''' Read from two table via a join where 
        ''' Persons1 has names and a key into the
        ''' second table GenderTypes
        ''' 
        ''' We hide the id column
        ''' </summary>
        ''' <returns></returns>
        Public Function Read() As DataTable
            Dim dt As New DataTable
            Dim ConnectionString As String =
                    "Data Source=KARENS-PC;Initial Catalog=People1;Integrated Security=True"
    
            Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
                Using cmd As New SqlCommand With {.Connection = cn}
                    cmd.CommandText =
                        <SQL>
                        SELECT  P.id ,
                                P.FirstName ,
                                P.LastName ,
                                G.GenderIdentifier,
                                G.GenderImage
                        FROM    Persons1 AS P
                                INNER JOIN GenderTypes AS G ON P.GenderIdentifier = G.GenderIdentifier
                        </SQL>.Value
    
                    cn.Open()
    
                    ' load data
                    dt.Load(cmd.ExecuteReader())
    
                    ' hide identifier
                    dt.Columns("id").ColumnMapping = MappingType.Hidden
                    ' hide seconary identifier which is needed for filtering
                    dt.Columns("GenderIdentifier").ColumnMapping = MappingType.Hidden
                End Using
            End Using
    
            Return dt
        End Function
    
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    This is an advance way of loading icon image to data by its gender. thanks mam for the effort, i would keep this as future reference. :)
    Friday, June 1, 2018 12:30 AM
  • Hi Tommy,

    Very clever. I did not propose it as answer, simply because the code from Cherry is more based on this what the OP wrote: "When i load student data from database to datagridview, i want to filter that records by its gender"

    But I find your code very clever. 

    (By the way, I think that clever part can also be implemented in the code of cherry.)

    :-) 


    Success
    Cor



    Totally agree. :)
    Friday, June 1, 2018 12:31 AM
  • Hi guys,

    I have a datagridview containing records including gender. I want to add a column for image (as first column). When i load student data from database to datagridview, i want to filter that records by its gender (if row data gender is male it will add male icon to image column from imagelist, and add female icon if the row gender is female).

    Hi zirjohn,

    According to your description, you just want to add different image based on gender in datagridviewimagecolumn, you can take a look the following code.

     Private Sub Frmdatagridview_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            
            Dim dt As New DataTable
            dt.Columns.Add("Id", GetType(Integer))
            dt.Columns.Add("Studengname", GetType(String))
            dt.Columns.Add("Gender", GetType(String))
    
            dt.Rows.Add(1, "A", "Male")
            dt.Rows.Add(2, "B", "Female")
            dt.Rows.Add(3, "C", "Male")
            dt.Rows.Add(4, "D", "Female")
            dt.Rows.Add(5, "E", "Male")
            dt.Rows.Add(6, "F", "Female")
            dt.Rows.Add(7, "G", "Male")
            DataGridView1.DataSource = dt
            Dim img As New DataGridViewImageColumn
            img.Name = "Image"
            DataGridView1.Columns.Add(img)
    
            AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting
        End Sub
     Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
            If e.RowIndex > -1 AndAlso e.ColumnIndex = Me.DataGridView1.Columns("Image").Index Then
    
                If Me.DataGridView1("Gender", e.RowIndex).Value IsNot Nothing Then
                    Dim s As String = Me.DataGridView1("Gender", e.RowIndex).Value.ToString()
    
                    Select Case s
                        Case "Female"
                            e.Value = Image.FromFile("D:\Image\1.jpg")
                        Case "Male"
                            e.Value = Image.FromFile("D:\Image\2.jpg")
                    End Select
                End If
            End If
        End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    This solved the problem. thanks cherry, keep on sharing :)
    Friday, June 1, 2018 12:33 AM