DataGridView Mouse Selection

I am using a DataGridView control in a Windows Forms application. When the user holds the control to select multiple items, it works fine. Now, when the user releases the controls and clicks (and holds the left mouse button) to start the drag and drop operation, the selection changes. How can I stop the selection from clearing when the user holds the left mouse button?

+4
source share
3 answers

I found this answer in Microsoft Forum

"To drag multiple rows, set DataGridView.MultiSelect to true and to the DataGridView.DragDrop event, delete and paste all rows in the DataGridView.SelectedRows collection."

This blog post also shows how to implement drag and drop on a DataGridView.


But it seems to me that you will have to inherit from the DataGridView and override these mouse events, as changing the selection will always be called differently.

  • protected virtual void OnCellMouseDown (DataGridViewCellMouseEventArgs e);
  • protected virtual void OnCellMouseUp (DataGridViewCellMouseEventArgs e);

Then you can catch the SelectionChanged event in OnMouseDown and make a selection in OnMouseUp. You will need to leave the point down so that you can select the correct item if it was not a drag.

You will also need to save the list of selected rows in the mouse event, and if it turns into a drag and drop event, you drag all these selected rows and select them with the mouse.

And don't forget to clear the list / copy of the selected lines in the mouse event.

+3
source
Good question. Although it may not be as easy to answer as you might have hoped, it should give you some idea on how to solve your problem: http://www.codeproject.com/KB/cpp/DataGridView_Drag-n-Drop. aspx
+1
source

I found one technique that works. After selecting the last cell (using ctrl or shift), you start dragging and dropping before releasing the mouse button, the selection will not change. Then in the frame, you can use the following method to get a list of selected cells:

private SC.ArrayList selectedCells() { SC.ArrayList cellsList = new SC.ArrayList(); Int32 selectedCellCount = dataViewImages.GetCellCount(DataGridViewElementStates.Selected); if (selectedCellCount > 0) { for (int i = 0;i < selectedCellCount; i++) { int cell = dataViewImages.SelectedCells[i].RowIndex*ShowImages.NumColumnsForWidth() + dataViewImages.SelectedCells[i].ColumnIndex; cellsList.Add(cell); } cellsList.Sort(); return cellsList; } else return null; } 
0
source

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


All Articles