Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete selected items from listbox

Tags:

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"); 
like image 523
Cristo Avatar asked Oct 31 '12 00:10

Cristo


People also ask

How do I add and remove items from my ListBox?

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 .


1 Answers

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.

like image 125
Patrick Quirk Avatar answered Oct 09 '22 17:10

Patrick Quirk