Reputation: 3583
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?
Upvotes: 4
Views: 6723
Reputation: 2289
I found one technique that works. Upon selecting the last cell (either with ctrl or shift) you start to drag before releasing the mouse button, the selection will not change. Then on the drop you can use the following method to get a list of the 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;
}
Upvotes: 0
Reputation:
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.
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.
Upvotes: 3
Reputation: 3504
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
Upvotes: 1