0
votes

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.

2

2 Answers

1
votes

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 (col == -1 || row == -1)
        {
            base.OnMouseDown(e);
            return;
        }

        // Make sure we select the row we are clicking on
        if (!Rows[row].Selected)
            base.OnMouseDown(e);

        if (col == 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);
        }
    }
}
0
votes

I'm not familiar with the DataGridView because i'm just using DevExpress-Framework, but i would expect that you have to save the selection on click of the checkBox. Later you can restore the selection.

List<DataRow> tempSelection = new List<DataRow>();
foreach (DataRow row in dataGridView.SelectedRows)
{
  tempSelection.Add(row);
}

//click your checkbox and do some stuff

foreach (DataRow row in tempSelection)
{
   row.Selected = true;
}

But do you think it is intuitive to click one checkbox and check multiple values? Maybe it's more intuitive to use a contextMenu which got a Button "CheckSelection". Think about it ;)