views:

784

answers:

3

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

A: 
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]);
    }
Russell Steen
I don't believe that will work because you will be changing the collection while you iterate. You will miss items.
JaredPar
Good question. Does editing "Items" change "SelectedItems"? Probably yes. In which case he'd need to read them into a temporary array. Edited to represent that.
Russell Steen
that was was I was thinking because the array is beoming smaller so I'll get an index-error
Kai
+1  A: 

Try this code instead at the end of the loop

foreach ( var item in new ArrayList(from.SelectedItems) ) {
  from.Items.Remove(item);
}
JaredPar
+2  A: 
private void MoveSelItems(ListBox from, ListBox to)
{
    while (from.SelectedItems.Count > 0)
    {
        to.Items.Add(from.SelectedItem[0]);
        from.Items.Remove(from.SelectedItem[0]);
    }
}
GenericTypeTea