user3716892 user3716892 - 1 month ago 8
C# Question

C# Don't allow DataGridViewCheckBoxColumn to remove selection

I have a DataGridView with the first column as a DataGridViewCheckBoxColumn.
I have SelectionMode set to FullRowSelect.
I have MultiSelect set to True.

I want to be able to select multiple rows and then check the first column. This will check or uncheck all the checkboxes that are currently selected; however, when I do this, the selection is removed and only the row whose checkbox I'm clicking on will be selected.

I other words, I don't want to remove the selection when clicking on the checkbox cell.

Answer

Make sure to set EditMode to EditProgrammatically

public class DataGridViewUsers : DataGridView
{
    protected override void OnMouseDown(MouseEventArgs e)
    {

        int col = HitTest(e.X, e.Y).ColumnIndex;
        int row = HitTest(e.X, e.Y).RowIndex;

        if (!Rows[row].Selected)
            base.OnMouseDown(e);

        if (col == 0 && row >= 0 && Rows[row].Selected)
        {
            DataGridViewCheckBoxCell cell = Rows[row].Cells[0] as DataGridViewCheckBoxCell;
            bool bIsSelection = cell != null && cell.Value != null && (bool)cell.Value;

            for (int i = 0; i < SelectedRows.Count; i++)
            {
                SelectedRows[i].SetValues(!bIsSelection);
            }
        }
        else
        {
            // Process normally
            base.OnMouseDown(e);
        }
    }
}