In this tutorial, we’ll learn How to change datagridview row color based on condition in c#.
Example 1:

Example:
UnitsInStock < 10 -> Row BackColor : Red, Row ForeColor:White
C# Code:
1 2 3 4 5 6 7 8 9 10 | foreach (DataGridViewRow dgvr in dgwProducts.Rows) { if (Convert.ToInt32(dgvr.Cells[3].Value) < 10) { dgvr.DefaultCellStyle.BackColor = Color.Red; dgvr.DefaultCellStyle.ForeColor = Color.White; } } |
Example 2:
Inside the CellFormatting event handler of the DataGridView, various conditions are used to compare the Cell value of the DataGridView Row and the Row color of the DataGridView is changed based on the conditions holding true.
The following Table shows the different quantity values and the corresponding color of the DataGridView Row.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private void dgwProducts_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { //Compare the value of second Column i.e. Column with Index 1. if (e.ColumnIndex == 3 && e.Value != null) { //Fetch the value of the second Column. int quantity = Convert.ToInt32(e.Value); //Apply Background color based on value. if (quantity == 0) { dgwProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; } if (quantity > 0 && quantity <= 20) { dgwProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; } if (quantity > 20 && quantity <= 100) { dgwProducts.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Orange; } } } |