Cristo Cristo - 2 months ago 13
C# Question

Delete selected items from listbox

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

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.