Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Drag item out of listview into a trash can?

How do I drag a item out of a Winforms-listview control onto another control (picture of trash can)?

UPDATE1:

I think the basic flow is:

  • for the ItemDrag event on the listview have a DoDragDrop
  • Then have a DragEnter event on the picturebox that captures that drag?

UPDATE2:

The basic flow (based on answers):

  • add 'ItemDrag' event to the listview.
  • add a 'DoDragDrop' inside the 'ItemDrag'
  • add 'DragEnter' event to the picturebox.
  • add a 'GetDataPresent' check inside the 'DragEnter' to check on the data type
  • add a 'DragDrop' event to the picturebox
  • add a 'GetDataPresent' check inside the 'DragEnter' to check on the data type
like image 207
John M Avatar asked May 20 '10 17:05

John M


2 Answers

Implement an event handler for the list view's ItemDrag event:

    private void listView1_ItemDrag(object sender, ItemDragEventArgs e) {
        DoDragDrop(e.Item, DragDropEffects.Move);
    }

And write the event handlers for the trash can:

    private void trashCan_DragEnter(object sender, DragEventArgs e) {
        if (e.Data.GetDataPresent(typeof(ListViewItem))) {
            e.Effect = DragDropEffects.Move;
        }
        // others...
    }

    private void trashCan_DragDrop(object sender, DragEventArgs e) {
        if (e.Data.GetDataPresent(typeof(ListViewItem))) {
            var item = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
            item.ListView.Items.Remove(item);
        }
        // others...
    }

You'll have to force the AllowDrop property for the PictureBox, it isn't available in the Properties window:

    public Form1() {
        InitializeComponent();
        trashCan.AllowDrop = true;
    }
like image 66
Hans Passant Avatar answered Oct 16 '22 13:10

Hans Passant


Look into DragEnter, DragLeave, and DragDrop. Also see example, Implementing Drag and Drop in ListView Controls

like image 34
KMån Avatar answered Oct 16 '22 13:10

KMån