Move items from one listbox to another

2019-01-26 21:17发布

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

4条回答
你好瞎i
2楼-- · 2019-01-26 21:41

Try this code instead at the end of the loop

foreach ( var item in new ArrayList(from.SelectedItems) ) {
  from.Items.Remove(item);
}
查看更多
在下西门庆
3楼-- · 2019-01-26 21:45
private void MoveSelItems(ListBox from, ListBox to)
{
    while (from.SelectedItems.Count > 0)
    {
        to.Items.Add(from.SelectedItem[0]);
        from.Items.Remove(from.SelectedItem[0]);
    }
}
查看更多
爷、活的狠高调
4楼-- · 2019-01-26 21:45
              for (int i = 0; i < ListBox3.Items.Count; i++)
               {
                    ListBox4.Items.Add(ListBox3.Items[i].Text);
                    ListBox3.Items.Remove(ListBox3.SelectedItem);

                }
查看更多
乱世女痞
5楼-- · 2019-01-26 21:55
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]);
    }
查看更多
登录 后发表回答