Wednesday, 7 July 2010

LISTVIEW WITH RE-ORDERING THROUGH DRAG AND DROP

  1. using System.Drawing;
  2. using System.Windows.Forms;
  3. namespace System.Windows.Forms // May need to set to something else
  4. {
  5. ///
  6. /// A ListView with DragDrop reordering.
  7. ///
  8. ///
  9. public class ListViewWithReordering : ListView
  10. {
  11. protected override void OnItemDrag(ItemDragEventArgs e)
  12. {
  13. base.OnItemDrag(e);
  14. //Begins a drag-and-drop operation in the ListView control.
  15. this.DoDragDrop(this.SelectedItems, DragDropEffects.Move);
  16. }
  17. protected override void OnDragEnter(DragEventArgs drgevent)
  18. {
  19. base.OnDragEnter(drgevent);
  20. int len = drgevent.Data.GetFormats().Length - 1;
  21. int i;
  22. for (i = 0; i <= len; i++)
  23. {
  24. if (drgevent.Data.GetFormats()[i].Equals("System.Windows.Forms.ListView+SelectedListViewItemCollection"))
  25. {
  26. //The data from the drag source is moved to the target.
  27. drgevent.Effect = DragDropEffects.Move;
  28. }
  29. }
  30. }
  31. protected override void OnDragDrop(DragEventArgs drgevent)
  32. {
  33. base.OnDragDrop(drgevent);
  34. //Return if the items are not selected in the ListView control.
  35. if (this.SelectedItems.Count == 0)
  36. {
  37. return;
  38. }
  39. //Returns the location of the mouse pointer in the ListView control.
  40. Point cp = this.PointToClient(new Point(drgevent.X, drgevent.Y));
  41. //Obtain the item that is located at the specified location of the mouse pointer.
  42. ListViewItem dragToItem = this.GetItemAt(cp.X, cp.Y);
  43. if (dragToItem == null)
  44. {
  45. return;
  46. }
  47. //Obtain the index of the item at the mouse pointer.
  48. int dragIndex = dragToItem.Index;
  49. ListViewItem[] sel = new ListViewItem[this.SelectedItems.Count];
  50. for (int i = 0; i <= this.SelectedItems.Count - 1; i++)
  51. {
  52. sel[i] = this.SelectedItems[i];
  53. }
  54. for (int i = 0; i < sel.GetLength(0); i++)
  55. {
  56. //Obtain the ListViewItem to be dragged to the target location.
  57. ListViewItem dragItem = sel[i];
  58. int itemIndex = dragIndex;
  59. if (itemIndex == dragItem.Index)
  60. {
  61. return;
  62. }
  63. if (dragItem.Index < itemIndex)
  64. itemIndex++;
  65. else
  66. itemIndex = dragIndex + i;
  67. //Insert the item at the mouse pointer.
  68. ListViewItem insertItem = (ListViewItem)dragItem.Clone();
  69. this.Items.Insert(itemIndex, insertItem);
  70. //Removes the item from the initial location while
  71. //the item is moved to the new location.
  72. this.Items.Remove(dragItem);
  73. }
  74. }
  75. }
  76. }

No comments:

Post a Comment