views:

2358

answers:

2

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?

+1  A: 

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

Matt Hanson
I saw that article yesterday...I wish that the selection would occur during "Click" instead of "Mouse Down". I already have drag/drop implemented, but I was just trying to fix it so that the user didnt have to hold down the mouse button when selecting the last item before dragging...
joek1975
+2  A: 

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.

tdyen