1

In windows Application I want to Set colors of different cells in datagridview based on the value range

Suppose value 1..22 : cell color should be green value 23.30 : cell color should be gray value >30 : cell color should be red

how can i do it..please suggest some code snippet? How can i do conditional formatting in datgridview in C#?

Jaswant Agarwal
  • 4,755
  • 9
  • 39
  • 49
  • Please also look at this answer that uses CellOnFormat http://stackoverflow.com/a/4067612/581414 – Ruskin May 19 '16 at 10:42

2 Answers2

1

See my answer for Windowsforms: How to draw lines/bars on a DataGridView?. The question provides an answer in VB.NET (should be easy enough to convert to C#).

Updated to suit question

Example:

private void dataGridView1_CellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
    if (e.Value > 0 && e.Value <= 22 )
    {
        e.Graphics.FillRectangle(Color.Green, e.CellBounds);
    }
    else if (e.Value > 22 && e.Value <= 30 )
    {
        e.Graphics.FillRectangle(Color.Grey, e.CellBounds);
    }
    else if (e.Value > 30)
    {
        e.Graphics.FillRectangle(Color.Red, e.CellBounds);
    }
    else
    {
        e.Graphics.FillRectangle(Color.White, e.CellBounds);
    }
}
Community
  • 1
  • 1
James
  • 80,725
  • 18
  • 167
  • 237
1

You can apply DataGridViewCellStyle object based on different condition

DataGridViewCellStyle cellstyle = new DataGridViewCellStyle();
cellstyle.BackColor = Color.Black;
cellstyle.ForeColor = Color.Yellow
dgvAllData.Rows[5].Cells[2].Style = cellstyle;
dgvAllData.Rows[3].Cells[2].Style = cellstyle;
dgvAllData.Rows[6].Cells[2].Style = cellstyle;