Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView moving items

I have another problem with ListView :( Now I need to move items in group (up, down, to the beginning, to the end), but ListView is displaying moved items always at the end.

Here is sample code for moving item to the beginning:

   if (1 == listView1.SelectedItems.Count)
    {

        ListViewItem item = listView1.SelectedItems[0];
        ListViewGroup gp = item.Group;

        int index;
        index = item.Index;

        if (index < listView1.Items.Count)
        {

            index = 0;

            listView1.Items.Remove(item);

            item.Group = gp;

            listView1.Items.Insert(index, item);
        }
    }

I tried google to find some solution, and I found someone else (http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/838f90cd-33d8-4c81-9ed9-85220b511afe) who had same problem like me, but his solution is not working :(

I considered using ObjectListView but I have modified ListView witch now supports drag & drop with WinAmp effect, onScroll events, scrolling synchronization etc.. and I don't want to lose this stuff :(

like image 322
Klinki Avatar asked Jul 22 '26 05:07

Klinki


1 Answers

Try this:

/// <summary>
/// Move the given item to the given index in the given group
/// </summary>
/// <remarks>The item and group must belong to the same ListView</remarks>
public void MoveToGroup(ListViewItem lvi, ListViewGroup group, int indexInGroup) {
    group.ListView.BeginUpdate();
    ListViewItem[] items = new ListViewItem[group.Items.Count + 1];
    group.Items.CopyTo(items, 0);
    Array.Copy(items, indexInGroup, items, indexInGroup + 1, group.Items.Count - indexInGroup);
    items[indexInGroup] = lvi;
    for (int i = 0; i < items.Length; i++)
        items[i].Group = null;
    for (int i = 0; i < items.Length; i++) 
        group.Items.Add(items[i]);
    group.ListView.EndUpdate();
}
like image 124
Grammarian Avatar answered Jul 23 '26 18:07

Grammarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!