0

I'm trying to change the image of a cell inside DataGridViewImageColumn when the value of another cell is OK or NO. I've created the column with this code

Dim NewImageProd As New DataGridViewImageColumn
NewImageProd.Image = My.Resources.Smile1
NewImageProd.Name = "IMAGE"
NewImageProd.ImageLayout = DataGridViewImageCellLayout.Zoom
NewImageProd.DisplayIndex = 0
NewImageProd.Width = 70
DGDati.Columns.Add(NewImageProd)

Later I've done the check with this code

For Idx = 0 To DGDati.RowCount - 1
    Select Case DGDati("OTHERVALUE", Idx).Value.ToString
        Case "OK"
            DGDati.Rows(Idx).Cells("IMAGE").Value = My.Resources.Smile2
        Case "NO"
            DGDati.Rows(Idx).Cells("IMAGE").Value = My.Resources.Smile3
    End Select
Next
Call DGDati.RefreshEdit()

But nothing happen. What am I doing wrong?

Stefano
  • 3
  • 5

1 Answers1

0

Use DataGridView.CellFormatting event that occurs when the contents of a cell need to be formatted for display. Using this event you don't need to refresh DataGridView or data.

Private Sub DGDati_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DGDati.CellFormatting

    If e.ColumnIndex = -1 Or e.RowIndex = -1 Then Exit Sub

    With Me.DGDati
        If .Columns(e.ColumnIndex).Name = "IMAGE" Then
            If .Rows(e.RowIndex).Cells("OTHER_VALUE").Value = "OK" Then
                e.Value = My.Resources.Smile2
            ElseIf .Rows(e.RowIndex).Cells("OTHER_VALUE").Value = "NO"
                e.Value = My.Resources.Smile3
            Else
                e.Value = My.Resources.Smile1
            End If
        End If
    End With

End Sub

Also follow advice in the comments to never reuse images from Resources like that.

tezzo
  • 10,858
  • 1
  • 25
  • 48