Moving ListViewItems Up & Down

前端 未结 6 2886
你的背包
你的背包 2021-02-20 16:45

I have a ListView (WinForms) in which i want to move items up and down with the click of a button. The items to be moved are the ones who are checked. So if item 2, 6 and 9 are

6条回答
  •  [愿得一人]
    2021-02-20 17:17

    Only for complete, based on 'Jason Larke' static helper solution:

    That solution don't move adjacent items, that can be done using a Stack so:

    private enum MoveDirection { Up = -1, Down = 1 };
    
    private static void MoveListViewItems(ListView sender, MoveDirection direction)
    {
    int dir = (int)direction;
    int opp = dir * -1;
    
    bool valid = sender.SelectedItems.Count > 0 &&
                    ((direction == MoveDirection.Down && (sender.SelectedItems[sender.SelectedItems.Count - 1].Index < sender.Items.Count - 1))
                || (direction == MoveDirection.Up && (sender.SelectedItems[0].Index > 0)));
    
    if (valid)
    {
    
    Stack aPila = new Stack();
    ListViewItem item = default(ListViewItem);
    foreach ( item in sender.SelectedItems) {
        aPila.Push(item);
    }
    
    for (int iaux = 1; iaux <= aPila.Count; iaux++) {
        {
        item  = (ListViewItem)aPila.Pop();
            int index = item.Index + dir;
            sender.Items.RemoveAt(item.Index);
            sender.Items.Insert(index, item);
    
            sender.Items[index + opp].SubItems[1].Text = (index + opp).ToString();
            item.SubItems[1].Text = (index).ToString();
        }
    }
    }
    

提交回复
热议问题