It is necessary that when the Ctrl key is pressed, the lines are highlighted, and the selection is not removed when you click again on one of the selected lines. That is - pressed Ctrl -> clicked on the line with the index 0 -> it became blue -> and no matter how many times we clicked on it, it will remain until Ctrl is pressed. How to do? Now I have this:

private void gridAction_KeyDown(object sender, KeyEventArgs e) { if (e.Control == true) gridAction.MultiSelect = true; } private void gridAction_KeyUp(object sender, KeyEventArgs e) { if (e.Control == false) gridAction.MultiSelect = false; } 

But I need to prohibit removing the selection from the line if Ctrl is pressed.

    1 answer 1

    I came up with such a bike.

    Add a form field:

     List<DataGridViewRow> selectedRows = new List<DataGridViewRow>(); 

    This will be the list of currently selected rows.

    Subscribe the DataGridView to the SelectionChanged event and place the following code in it:

     private void DataGridView_SelectionChanged(object sender, EventArgs e) { // Нажата клавиша Control if ((ModifierKeys & Keys.Control) == Keys.Control) { if (dataGridView.SelectedRows.Count > selectedRows.Count) { selectedRows.Clear(); selectedRows.AddRange(dataGridView.SelectedRows.Cast<DataGridViewRow>()); } else { foreach (var row in selectedRows) row.Selected = true; } } else { selectedRows.Clear(); } } 

    The logic is this. With the Control key pressed, if there are more selected lines than in our list, then we add all these selected lines to it. If the selected lines become less (that is, the user has clicked on the previously selected line), then we restore the selection from our list.

    When the selection of lines changes without the Control key being pressed, we clear our list.