pinhead pinhead - 1 month ago 11
C# Question

Setting z-index of multiple background colors in DataGridView rows/cells

I have enabled full row selection in my DataGridView so that when a row is clicked on, the entire row is highlighted blue. To achieve this I used the following code:

this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;


However, I also occasionally change the background color of a row or cell based on certain events. To do this, I'm just accessing the row's
DefaultCellStyle
and setting the
BackColor
to green. However, whenever I change the color and the row is already selected, the blue selected highlight has priority and it is not apparent that the row has any cells that are green. I'd like the green cells to display on top of the blue highlighted row.

Is there anyway to set the priority/z-index of my rows/cells so that the
SelectionMode
property is always placed in the background and my other colors are always layered on top?

Answer

For the rows or cells which you change their BackColor, set SelectionBackColor to the same color which you used as BackColor.

For example for a specific row:

dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
dataGridView1.Rows[0].DefaultCellStyle.SelectionBackColor = Color.Red;

Or for a specific cell:

this.dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Red;
this.dataGridView1.Rows[0].Cells[0].Style.SelectionBackColor = Color.Red;