Moving ListViewItems Up & Down

前端 未结 6 2862
你的背包
你的背包 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条回答
  •  Happy的楠姐
    2021-02-20 17:15

        private void MoveItems(ListView sender, MoveDirection direction)
        {
            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)
            {                
                bool start = true;
                int first_idx = 0;                
                List items = new List();
    
                // ambil data
                foreach (ListViewItem i in sender.SelectedItems)
                {
                    if (start)
                    {
                        first_idx = i.Index;
                        start = false;
                    }
                    items.Add(i);
                }
    
                sender.BeginUpdate();
    
                // hapus
                foreach (ListViewItem i in sender.SelectedItems) i.Remove();
    
                // insert
                if (direction == MoveDirection.Up)
                {
                    int insert_to = first_idx - 1;
                    foreach (ListViewItem i in items)
                    {
                        sender.Items.Insert(insert_to, i);
                        insert_to++;
                    }                    
                }
                else
                {
                    int insert_to = first_idx + 1;
                    foreach (ListViewItem i in items)
                    {
                        sender.Items.Insert(insert_to, i);
                        insert_to++;
                    }   
                }                
                sender.EndUpdate();
            }            
        }
    

    Your answers don't work well fren. Here my code work perfect...

提交回复
热议问题