Moving ListView Items

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

Here is a sample code to move an element 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 the same problem as me, but his solution does not work :(

I reviewed the use of ObjectListView, but I changed the ListView, it now supports drag and drop using the WinAmp effect, onScroll events, scroll scrolling, etc., and I don't want to lose this stuff :(

+3
3

:

/// <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();
}
+2

, ,

listView1.Items.Count - 1

, 1 )

0

, , - . , , intial if. 1 , , , . , < =

, 0 . , Index = 0 if.

Not sure if this will solve the problem though ...

0
source

Source: https://habr.com/ru/post/1713679/


All Articles