views:

301

answers:

3

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
+2  A: 

EDIT This applies only if you want shell integrated drag-and-drop. If you are not integrating with the shell, and only dragging and dropping between things in your own app, then this answer does not apply. My apologies for the confusion.


You need to support drag-n-drop in your app or control. This involves some COM interop.

It seems a little complicated at first, but once you get the basic skeleton up, it's not that hard to implement. Also there's a nice guide right here, that tells you how:

http://blogs.msdn.com/adamroot/pages/shell-style-drag-and-drop-in-net-wpf-and-winforms.aspx

Cheeso
There should be no COM interop necessary to support drag-drop within the application, AFAIK (note *"onto another control (picture of trash can)"*.
Fredrik Mörk
Wow @Cheeso - that definitely looks complex - might be useful later for more advanced visuals.
John M
Ahh, Fredrik, you are correct!! I mis-interpreted the question. The COM interop is necessary only when doing shell-integrated Drag/drop. My bad. I've updated the post with a note on that.
Cheeso
+5  A: 

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;
    }
Hans Passant
Thanks @Hans! The samples really helped to get me on the right path.
John M
+2  A: 

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

KMan
Thanks @KMan the MSDN links are helpful.
John M