I guess you will need to move the items separately:
List<object> itemsToRemove = new List<object>();
foreach (var item in listbox2.SelectedItems)
{
listbox1.Items.Add(item);
itemsToRemove.Add(item);
}
foreach (var item in itemsToRemove)
{
listbox2.Items.Remove(item);
}
This will move any selected items from listbox2
to listbox1
. The itemsToRemove
list is used as a temporary storage since you cannot modify a collection while iterating over it; while iterating we just add references to the items to be removed into a temporary list, then we iterate over that list and remove the items.
In order to handle the case when no items are selected, I would set up an event handler for the SelectedIndexChanged
event, and set the Enabled
property of the button:
theButton.Enabled = (listbox2.SelectedItems.Count > 0);