I am using a DataGridView control in a Windows Forms application. When a user holds down control to select multiple items, it works fine. Now when the user releases control and clicks (and holds down the left mouse button) to start a drag operation, the selection changes. How can I stop the selection from clearing when the user holds down the left mouse button?
Good question. Although this may not be as simple of an answer as you may have been hoping for, it should give you some good insight at how to go about solving your problem: http://www.codeproject.com/KB/cpp/DataGridView_Drag-n-Drop.aspx
I found this answer in a Microsoft Forum
"In order to drag and drop multiple rows, Set DataGridView.MultiSelect to true and in the DataGridView.DragDrop event, remove and insert all the rows in the DataGridView.SelectedRows collection."
This blog entry 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 the selection change will always get called otherwise.
- protected virtual void OnCellMouseDown(DataGridViewCellMouseEventArgs e);
- protected virtual void OnCellMouseUp(DataGridViewCellMouseEventArgs e);
Then you can intercept the SelectionChanged event in the OnMouseDown and do the selection in the OnMouseUp instead. You will have to keep the down location point so you can select the correct item if it was not a drag drop.
You will also have to maintain a list of the selected rows in the mouse down event and if it turns into a drag drop event you drag all these selected rows and select them on the mouse up.
And don't forget to clear the list/copy of selected rows on the mouse up event.