4

I have a ListView with DragDrop function. I want the dragged item to keep selected after the DragDrop.

I have this code (for the DragDrop)

private void commandListView_DragDrop(object sender, DragEventArgs e)
{
    Point point = commandListView.PointToClient(new Point(e.X, e.Y));
    int index = 0;

    try
    {
        index = commandListView.GetItemAt(point.X, point.Y).Index;
    }
    catch (Exception)
    {
    }

    if (index < 0)
    {
        index = commandListView.Items.Count - 1;
    }

    ListViewItem data = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;
    commandListView.Items.Remove(data);
    commandListView.Items.Insert(index, data);
}

And i tried to use this this to select the item again but it doesnt work

data.Selected = true;
data.Focused = true;

Then i tested to see if i could focus on the first item in the ListView

commandListView.Items[0].Selected = true;
commandListView.Items[0].Focused = true;

but it didnt work either, the selected item doesnt change. its always the old index where the dragged item was before the dragdrop.

PS. I'm using WinForms

@Update

I already tried to use

commandListView.Focus();

but it didnt worked

Just to clarify the dragdrop is happening inside the same ListView, i'm dragging items to change their order.

2 Answers2

1

I found a solution; i was using the MouseDown event to start the DragDrop operation.

Now i use the ItemDrag event and everything works fine, actually i dont even need to focus the item, it's done automatically.

0

For those still trying to find a solution:

int counter = ...; // your code to find index of wanted ListView-Item.

ListVieuwName.Focus(); //First: activate focus on the entire ListView.

ListVieuwName.Items[counter].Selected = true; //Next: select your wanted ListView-Item.

This should do it...

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77