Search code examples
vb.netdatagridviewcell-formatting

Highlighting DataGridView Row


I want to highlight DataGridView rows depending on value. If value is validated then green if not then red.
I get the green and red when cell has not been formatted before. However when I go back to the green row and change its value which is not validated one cell does not change to red. It stays green.
See the pictures:
1)Without any entry
enter image description here
2)Entered Validated value
enter image description here
3)Went back and entered wrong value
enter image description here
As you can see only first cell is red, but I want whole row to be red.
I am formatting cells in CellValidating event. Here's the code:

Private Sub dgvItems_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles dgvItems.CellValidating
    If e.ColumnIndex = ValueColumnIndex Then
        If Not ValidateValue(e.FormattedValue) Then
            Me.dgvItems.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LightPink
            Me.dgvItems.DefaultCellStyle.SelectionBackColor = Color.LightPink
            Me.dgvItems.DefaultCellStyle.SelectionForeColor = Color.Black
            e.Cancel = True
        Else
            Me.dgvItems.DefaultCellStyle.SelectionBackColor = SystemColors.Highlight
            Me.dgvItems.DefaultCellStyle.SelectionForeColor = SystemColors.HighlightText
            Me.dgvItems.Rows(rowIndex).DefaultCellStyle.BackColor = Color.LightGreen
            Me.dgvItems.Rows(rowIndex).DefaultCellStyle.ForeColor = Color.Black
        End If
    End If
End Sub

Any help appreciated. Thanks.


Solution

  • On the Properties of the DataGridView, look for Focus > RowValidating, as illustrated in the image below.

    enter image description here

    Something like this should do it for you.

    Sub DataGridView1_RowValidating(ByVal sender As Object, ByVal e As DataGridViewCellCancelEventArgs)
    
       Dim drv As DataRowView
       Dim c As Color
         If drv.Item("Gender").ToString = "M" Then
           c = Color.LightBlue
         Else
           c = Color.Pink
         End If
         e.CellStyle.BackColor = c
    
    End Sub