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");
When a user enters text into a TextBox and clicks on the Add Button the TextBox text will be shown in the ListBox. After that select text from the ListBox and click on the Delete Button to remove the text from the list. All you have to do is implement and hook it up to your website. First, start Visual Studio .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With