1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
//Begins a drag-and-drop operation in the ListView control.
listView1.DoDragDrop(listView1.SelectedItems, DragDropEffects.Move);
}
private void listView1_DragEnter(object sender, DragEventArgs e)
{
int len=e.Data.GetFormats().Length - 1;
int i;
for (i = 0; i <= len; i++)
{
if (e.Data.GetFormats()[i].Equals("System.Windows.Forms.ListView+SelectedListViewItemCollection"))
{
//The data from the drag source is moved to the target.
e.Effect = DragDropEffects.Move;
}
}
}
private void listView1_DragDrop(object sender, DragEventArgs e)
{
//Return if the items are not selected in the ListView control.
if (listView1.SelectedItems.Count == 0)
{
return;
}
//Returns the location of the mouse pointer in the ListView control.
Point cp = listView1.PointToClient(new Point(e.X, e.Y));
//Obtain the item that is located at the specified location of the mouse pointer.
ListViewItem dragToItem = listView1.GetItemAt(cp.X, cp.Y);
if (dragToItem == null)
{
return;
}
//Obtain the index of the item at the mouse pointer.
int dragIndex = dragToItem.Index;
ListViewItem[] sel=new ListViewItem[listView1.SelectedItems.Count];
for (int i=0; i <= listView1.SelectedItems.Count - 1; i++)
{
sel[i] = listView1.SelectedItems[i];
}
for (int i=0; i < sel.GetLength(0); i++)
{
//Obtain the ListViewItem to be dragged to the target location.
ListViewItem dragItem = sel[i];
int itemIndex = dragIndex;
if (itemIndex == dragItem.Index)
{
return;
}
if (dragItem.Index < itemIndex)
itemIndex++;
else
itemIndex = dragIndex + i;
//Insert the item at the mouse pointer.
ListViewItem insertItem = (ListViewItem)dragItem.Clone();
listView1.Items.Insert(itemIndex, insertItem);
//Removes the item from the initial location while
//the item is moved to the new location.
listView1.Items.Remove(dragItem);
}
} |