Delete selected items from listbox

Cristo picture Cristo · Oct 31, 2012 · Viewed 84.6k times · Source

I want to do that but, the listbox changes on every deletion, so it throws runtime exception even if I tried to do a new object.

I tried like this:

ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstClientes);
   selectedItems = lstClientes.SelectedItems;
if (lstClientes.SelectedIndex != -1)
{ 
    foreach (string s in selectedItems)
        lstClientes.Items.Remove(s);
}
else
    MessageBox.Show("Debe seleccionar un email");

Answer

Patrick Quirk picture Patrick Quirk · Oct 31, 2012

You can't modify a collection while iterating (using a foreach) through it. Instead use a reverse for loop:

ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(lstClientes);
selectedItems = lstClientes.SelectedItems;

if (lstClientes.SelectedIndex != -1)
{ 
    for (int i = selectedItems.Count - 1; i >= 0; i--)
        lstClientes.Items.Remove(selectedItems[i]);
}
else
    MessageBox.Show("Debe seleccionar un email");

Using a reverse loop ensures you don't skip over any after removing them.