Search code examples
c#datagridview

C# - Change row color when I select a cell


I have a dataGridView and I want to change the color of the selected row when I click on the cell. I did this with the below code but my problem is when I select the second row then the first row didn't change back to the default style.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
  dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
  dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}

Could you please help me?


Solution

  • You can store the last colored cell and restore it's coloring when another is activated.

    private System.Windows.Forms.DataGridViewRow lastColoredRow = null;
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if(lastColoredRow!=null) {
            // Restore the coloring as needed
            lastColoredRow.DefaultCellStyle.BackColor = Color.White;
            lastColoredRow.DefaultCellStyle.ForeColor = Color.Black;
        }
        dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
        dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
        lastColoredRow = dataGridView1.CurrentRow;
    }