Thursday, July 28, 2011

How to Change Grid View Cell Back Color

In C#.NET windows application, suppose you want to set color your Data-grid cell based on some criteria or value. The code you need to do is as follows:

int colIndex = 0, rowIndex = 0;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
      colIndex = 9;
      rowIndex = dgvr.Index;
      if (dataGridView1["MatchField", rowIndex].Value != null)
      {
              if (dataGridView1["Match
Field", rowIndex].Value.ToString() == "NotMatch")
              {
                     dataGridView1[colIndex, rowIndex].Style.BackColor = Color.Red;
              }
      }
}


Here in my Data Grid I have marked column 9 which name is "MatchField" and if that column value is "NotMatch" then i made that cell back color into Red.