How to conditionally change the BackColor of a Row in DataGridView in VB.NET

Here is a working code for changing the DataGridView row colors based on condition.

In this code I am checking if the Cell called “Date Closed” is present or not, so if a row item has a closed date present then I would like to show that row in Red Color.

It is easy to do, just put your conditions in the If End If block shown below according to your needs


Private Sub dgr_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgr.CellFormatting

        If e.RowIndex >= 0 Then
            If IsDate(dgr.Rows(e.RowIndex).Cells(“Date Closed”).Value) Then

                e.CellStyle.ForeColor = Color.Red
            End If

        End If

    End Sub


Here is the snapshot of the above code in action.


Change the DataGridView Rowcolor conditionally