I have loaded the data from database to datagridview and have two columns target value and volume where volume >target value that volume cell should be in green color and volume < target value then volume should be in red color. I tried it but I am not able to do it.
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { if (dataGridView1.Rows.Count > 0 && dataGridView1.Columns.Count > 0) { foreach (DataGridViewRow r in dataGridView1.Rows) { if (Volume > target value) { cell.Style.BackColor = Color.AliceBlue; }
I may suggest NOT looping over each rows EACH time CellFormating is called, because it is called everytime A SINGLE ROW need to be refreshed.
Private Sub dgv_DisplayData_Vertical_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv_DisplayData_Vertical.CellFormatting Try If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "6" Then e.CellStyle.BackColor = Color.DimGray End If If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "5" Then e.CellStyle.BackColor = Color.DarkSlateGray End If If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "4" Then e.CellStyle.BackColor = Color.SlateGray End If If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "3" Then e.CellStyle.BackColor = Color.LightGray End If If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "0" Then e.CellStyle.BackColor = Color.White End If Catch ex As Exception End Try End Sub
You need to do this
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { foreach (DataGridViewRow Myrow in dataGridView1.Rows) { //Here 2 cell is target value and 1 cell is Volume if (Convert.ToInt32(Myrow .Cells[2].Value)<Convert.ToInt32(Myrow .Cells[1].Value))// Or your condition { Myrow .DefaultCellStyle.BackColor = Color.Red; } else { Myrow .DefaultCellStyle.BackColor = Color.Green; } } }
Meanwhile also take a look at Cell Formatting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With