Moving ListViewItems Up & Down

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

    This one is with wrapping, so if you move item at index 0 down it will come to last position, and if you move last item up it will be first on list:

        public static class ListExtensions
        {
            public static void MoveUp(this IList list, int index)
            {
                int newPosition = ((index > 0) ? index - 1 : list.Count - 1);
                var old = list[newPosition];
                list[newPosition] = list[index];
                list[index] = old;
            }
    
            public static void MoveDown(this IList list, int index)
            {
                int newPosition = ((index + 1 < list.Count) ? index + 1 : 0);
                var old = list[newPosition];
                list[newPosition] = list[index];
                list[index] = old;
            }
        }
    

提交回复
热议问题