Move items from one listbox to another

13,473

Solution 1

Try this code instead at the end of the loop

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

Solution 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]);
    }
}

Solution 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]);
    }

Solution 4

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

                }
Share:
13,473
Kai
Author by

Kai

we all have our segfaults.

Updated on June 07, 2022

Comments

  • Kai
    Kai almost 2 years

    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