You can change the row color of a C# DataGridView based on a value in a specific column by handling the CellFormatting event of the DataGridView. Here is an example that demonstrates how to change the row color of a DataGridView based on the value in the “Status” column:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name == "Status") { if (e.Value != null) { string status = e.Value.ToString(); if (status == "Active") { e.CellStyle.BackColor = Color.Green; } else if (status == "Inactive") { e.CellStyle.BackColor = Color.Red; } } } } |
In this example, the CellFormatting event is handled and the column name is checked if it’s “Status” column, if it is the value is read and if the value is “Active” the row color is set to Green otherwise if the value is “Inactive” the row color is set to red.
You can also use DataGridView.DefaultCellStyle property to change the default style of all cells in a datagridview.
It’s important to note that this method is called for every cell in the DataGridView, so it can impact performance if you have a large number of rows in your DataGridView.