Kai
Kai

Reputation: 5910

Move items from one listbox to another

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

Upvotes: 3

Views: 13584

Answers (4)

Simani
Simani

Reputation: 11

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

                }

Upvotes: 1

Russell Steen
Russell Steen

Reputation: 6612

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

Upvotes: 1

djdd87
djdd87

Reputation: 68516

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

Upvotes: 2

JaredPar
JaredPar

Reputation: 755457

Try this code instead at the end of the loop

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

Upvotes: 3

Related Questions