Question

I have a DataGridView bound to a list of objects, and I'm setting a dynamic cell background colour using the CellFormatting event, as in this answer. This works well for every column except the DataGridViewCheckboxColumn. When I click inside this cell (but outside the checkbox) the cell background changes to the default white.

Visually it looks like cell selection is occurring, despite my best efforts to stop it. My cell formatting code sets the SelectionBackColor as well as the BackColor. I've disabled cell selection using the CellStateChanged event, and none of the other columns are selectable:

private void PlayerGrid_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
    if (e.StateChanged == DataGridViewElementStates.Selected)
       e.Cell.Selected = false;
}

Is there an extra workaround to override the cell behaviour for checkboxes?

Was it helpful?

Solution

I've found a workaround by adding the following code to the CellStateChanged event:

if (e.Cell is DataGridViewCheckBoxCell)
      e.Cell.Style.BackColor = BackgroundColor(e.Cell.RowIndex);

(BackgroundColor() calculates the cell background colour based on the row.)

This cures the problem, but could cause performance issues for larger or virtual tables, by causing creation of extra style objects.

OTHER TIPS

I rather like this approach for what I'm doing. It's able to agnostically change background color (including Checkbox) of ANY of the DataGridView cells with a mouse click or Tab--for example purposes--to highlight the currently selected cell. I found other approaches oddly did not color the background of the checkbox as other cell types were colored. In my example, I'm using this approach in the CellFormatting event but I believe a similar syntax can be duplicated with success elsewhere. Also, I believe this more closely answers the OPs question as it relates to, specifically, the CellFormatting event.

void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
 {


if (W.mf.dgv.CurrentCell != null && e.RowIndex==W.mf.dgv.CurrentCell.RowIndex & e.ColumnIndex==W.mf.dgv.CurrentCell.ColumnIndex)
         {

                 W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = Color.YellowGreen;

         }
         else
         {
                 W.mf.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.SelectionBackColor = W.mf.dgv.DefaultCellStyle.SelectionBackColor;

         }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top