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");
You can’t modify a collection while iterating (using a
foreach) through it. Instead use a reverseforloop:Using a reverse loop ensures you don’t skip over any after removing them.