Disable user from selecting multiple rows that are not next to each other?

In the DataGridView user can select several rows that are not adjacent to each other, holding control and selecting different rows. My question has two parts.

Firstly, it keeps control by default in the only way that the user can select multiple rows that are not adjacent to each other, how is it? Secondly, how can I disable this behavior?

+4
source share
3 answers

First, does it hold control by default in the only way that it can select multiple rows that are not adjacent to each other?

No, you can get it in your own way by doing Events . These links can help you achieve what you want: this and this .

Secondly, how can I disable this behavior?

Disable Ctrl + click so that the user cannot select multiple cells, rows or columns that are separate from each other. You can do this by overriding the OnMouseDown event. Obviously, for this you have to go to your own (datagridview inherited) control. In this case, override the OnMouseDown .. event.

  protected override void OnMouseDown(MouseEventArgs e) { if ((Control.ModifierKeys & Keys.Control) == Keys.Control) { } else { base.OnMouseDown(e); } } 

Hope this helps.

+3
source

Use a multiSellect property like this

multiSelect=false

+1
source

Without the need to create a custom datagrid, you can track the selected row indices and deselect the row if it is not valid in the RowStateChanged event. This involves choosing a cap.

You will also need to add some validation logic when selecting a row to ensure that it does not create a gap in adjacent rows. For example, row 1,2,3 is selected, then row 2 is canceled, so you will either need to prohibit this, or deselect row 3 or row 1.

 public List<int> selectedIndexes = new List<int>(); private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e) { if (e.StateChanged == DataGridViewElementStates.Selected) { //selected if (e.Row.Selected) { int newRowIndex = e.Row.Index; //if other rows selected make sure adjacent selection exists if (selectedIndexes.Count() > 0) { if (selectedIndexes.Contains(newRowIndex - 1) || selectedIndexes.Contains(newRowIndex + 1)) { //allow selection selectedIndexes.Add(newRowIndex); } else { //cancel selection e.Row.Selected = false; } } else { //first selection so allow it selectedIndexes.Add(newRowIndex); } } else if( !e.Row.Selected) { //row deselected (need to add logic to remove non adjacent rows to be unselected as well) selectedIndexes.Remove(e.Row.Index); } } 

}

0
source

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


All Articles