Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing datagridview cell color based on condition

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;             }  
like image 661
preethi Avatar asked Oct 15 '13 11:10

preethi


2 Answers

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 
like image 171
Simon Avatar answered Sep 23 '22 05:09

Simon


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

like image 42
Rohit Avatar answered Sep 23 '22 05:09

Rohit