简体   繁体   中英

c# Drag & drop in listview

I've got a listbox from which I'm dragging into the ListView. Now I have groups in the ListView so when the item from the ListView is dropped at the point of the listviewgroup it has to add it under that group.

This is the code which handles the drop.

    private void lstvPositions_DragDrop(object sender, DragEventArgs e)
    {

        var group = lstvPositions.GetItemAt(e.X, e.Y);
        var item = e.Data.GetData(DataFormats.Text).ToString();
        lstvPositions.Items.Add(new ListViewItem {Group = group.Group, Text = item});

    }

I didn't find a function that could give the groupitem, so I used GetItemAt from which I also have access to the listviewgroup.

But GetItemAt always returns null.

Am I doing something wrong? Is there a better way to accomplish this?

First, I assume you're using a ListView, not a ListBox, as ListBox does not contain a GetItemAt member.

To solve your problem, convert the point to local coordinates:

private void lstvPositions_DragDrop(object sender, DragEventArgs e)
{
   var localPoint = lstvPositions.PointToClient(new Point(e.X, e.Y));
   var group = lstvPositions.GetItemAt(localPoint.X, localPoint.Y);
   var item = e.Data.GetData(DataFormats.Text).ToString();
   lstvPositions.Items.Add(new ListViewItem {Group = group.Group, Text = item});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM