Changing datagridview cell color dynamically

fifamaniac04 picture fifamaniac04 · Jul 18, 2013 · Viewed 136.6k times · Source

I have a dataGridView object that is populated with data. I want to click a button and have it change the color of the background of the cell. This is what I currently have

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewColumn col in dataGridView1.Columns)
    {
            //row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work
            //col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work
        dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work
    }
} 

ALL of these three cause the table to be redrawn over itself in an overlapping manner and trying to re-size the tables becomes a mess. when clicking on a cell, the value remains highlighted and the backcolor doesn't change.

Q: How can I change the backcolor of an individual cell after the table exists?

Answer

Ehsan picture Ehsan · Jul 18, 2013

This works for me

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;