Move items from one listbox to another

2019-01-26 21:14发布

问题:

I'd like to move items from one list view to another. adding them to the second one works but the moved entries don't get removed at all.

private void MoveSelItems(ListBox from, ListBox to)
    {
        for (int i = 0; i < from.SelectedItems.Count; i++)
        {
            to.Items.Add(from.SelectedItems[i].ToString());
        }

        from.Items.Remove(to.SelectedItem);
    }

I'm using C# / Winforms / -NET 3.5

回答1:

Try this code instead at the end of the loop

foreach ( var item in new ArrayList(from.SelectedItems) ) {
  from.Items.Remove(item);
}


回答2:

private void MoveSelItems(ListBox from, ListBox to)
{
    while (from.SelectedItems.Count > 0)
    {
        to.Items.Add(from.SelectedItem[0]);
        from.Items.Remove(from.SelectedItem[0]);
    }
}


回答3:

private void MoveSelItems(ListBox from, ListBox to)
    {
        for (int i = 0; i < from.SelectedItems.Count; i++)
        {
            to.Items.Add(from.SelectedItems[i].ToString());
            from.Items.Remove(from.SelectedItems[i]);
        }
    }

Though

Items.RemoveAt(i) is probably faster, if that matters.

You may need to create a holding list.

    //declare
    List<Object> items = new List<Object>();
    for (int i = 0; i < from.SelectedItems.Count; i++)
    {
        items.Add(from.SelectedItems[i]);
    }
    for (int i = 0; i < items.Count; i++)
    {
        to.Items.Add(items[i].ToString());
        from.Items.Remove(items[i]);
    }


回答4:

              for (int i = 0; i < ListBox3.Items.Count; i++)
               {
                    ListBox4.Items.Add(ListBox3.Items[i].Text);
                    ListBox3.Items.Remove(ListBox3.SelectedItem);

                }