0

I am trying to remove a specific item on my list (people) when button (remove) is clicked. Instead, only the display on the listview (listName) is removed. When I create another name, the previous names that I had removed are displayed on the lisview again.

public void remove(object sender, EventArgs e)
    {
        foreach (ListViewItem eachItem in listName.SelectedItems)
        {
            listName.Items.Remove(eachItem);
        }
    }
Cievlh
  • 1
  • 3

1 Answers1

0

You should make a list of items to remove while enumerating, then use that list to actually remove them, to avoid modifying the collection while enumerating (since modifying Items is really also modifying SelectedItems which you are currently enumerating):

public void remove(object sender, EventArgs e)
{
    var itemsToDelete = new List<ListViewItem>();
    foreach (ListViewItem eachItem in listName.SelectedItems)
    {
        itemsToDelete.Add(eachItem);
    }
    foreach (ListViewItem eachItem in itemsToDelete)
    {
        listName.Items.Remove(eachItem);
    }
}
Tim
  • 5,940
  • 1
  • 12
  • 18