Saturday, May 24, 2008

Changing Color in DataGridView based on content

The following is how it can be achieved:

Private Sub dgView_RowPostPaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgView.RowPostPaint
Dim vValue As String = ""
Dim vCnt As Integer = dgView.Rows.Count
Dim cellCnt As Integer

If Me.Visible Then
If vCnt > 0 Then
vValue = dgView.Rows(e.RowIndex).Cells(3).Value
If IsNothing(vValue) = False Then
If LCase(vValue).Contains("err") Then
For cellCnt = 0 To (dgView.Rows(e.RowIndex).Cells.Count - 1)
dgView.Rows(e.RowIndex).Cells(cellCnt).Style.ForeColor = Color.Red
End If
End If
End If

End If
End Sub

In this example, I am looking at the fourth column and if it contains the word "err", the words will be turned red.

An earlier routine using RowsAddEvent did not work when I converted from an unsorted data to sorted data.

No comments: