Moving ListViewItems Up & Down

前端 未结 6 2860
你的背包
你的背包 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:29

    Code with wrap around:

        private enum MoveDirection { Up = -1, Down = 1 };
    
        private void MoveListViewItems(ListView sourceListView, MoveDirection direction)
        {
            int dir = (int)direction;
    
            foreach (ListViewItem lvi in sourceListView.SelectedItems)
            {
                int index = lvi.Index + dir;
                if(index >= sourceListView.Items.Count)
                    index = 0;
                else if(index < 0)
                    index = sourceListView.Items.Count + dir;
    
                sourceListView.Items.RemoveAt(lvi.Index);
                sourceListView.Items.Insert(index, lvi);
            }
        }
    

提交回复
热议问题