tags:

views:

157

answers:

2

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#?

+1  A: 

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);
    }
}
James
+1  A: 

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;