To change the color of a cell in a DataGridView based on a condition, you can use the CellFormatting
event of the DataGridView. This event is raised when a cell is about to be painted, and allows you to customize the appearance of the cell.
Here is an example of how to use the CellFormatting
event to change the background color of a cell based on its value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public Form1() { InitializeComponent(); dataGridView1.ColumnCount = 2; dataGridView1.Columns[0].Name = "Value"; dataGridView1.Columns[1].Name = "Text"; dataGridView1.Rows.Add(25, "Low"); dataGridView1.Rows.Add(75, "High"); dataGridView1.Rows.Add(50, "Medium"); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 0 && e.RowIndex != this.dataGridView1.NewRowIndex) { int value = (int)e.Value; if (value < 50) { e.CellStyle.BackColor = Color.Green; } else if (value >= 50 && value < 75) { e.CellStyle.BackColor = Color.Yellow; } else { e.CellStyle.BackColor = Color.Red; } } } |
Output:
To change the color of a row in a DataGridView based on the value of a cell in the row, you can use the CellFormatting
event of the DataGridView. This event is raised when a cell is about to be painted, and allows you to customize the appearance of the cell.
Here is an example of how to use the CellFormatting
event to change the background color of a row based on the value of a cell in the row:
To change the color of a row in a DataGridView based on the value of a cell in the row, you can use the CellFormatting
event of the DataGridView. This event is raised when a cell is about to be painted, and allows you to customize the appearance of the cell.
Here is an example of how to use the CellFormatting
event to change the background color of a row based on the value of a cell in the row:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 0 && e.RowIndex != this.dataGridView1.NewRowIndex) { int value = (int)dataGridView1[0, e.RowIndex].Value; if (value < 50) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green; } else if (value >= 50 && value < 75) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; } else { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; } } } |
Output: