Background Color DataGridViewCheckboxCell

I have an DataGridViewassociated with a list of objects, and I set the background color of a dynamic cell using an event CellFormatting, as in this answer . This works well for every column except DataGridViewCheckboxColumn. When I click inside this cell (but outside the checkbox), the background of the cell changes to white by default.

Visually, it seems like cell selection is taking place, despite all my efforts to stop it. My cell formatting code sets SelectionBackColoras well BackColor. I turned off cell selection using the event CellStateChanged, and none of the other columns can be selected:

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

Is there an additional workaround to override cell behavior for checkboxes?

+3
source share
2 answers

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

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

( BackgroundColor()calculates the background color of the cell based on the row.)

This fixes the problem, but can cause performance problems for large or virtual tables, causing the creation of additional style objects.

+2
source

, . ( ) DataGridView Tab - , . , , . CellFormatting, , . , , OPs, , , CellFormatting.

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;

         }
}
0

Source: https://habr.com/ru/post/1763636/


All Articles