Collection was modified; enumeration may not execute error when removing a ListItem from a LIstBox

后端 未结 9 618
抹茶落季
抹茶落季 2020-11-29 12:30

I have two ListBoxes, lstAvailableColors and lstSelectedColors. Between each listbox are two buttons, Add and Remove. When a color or colors is selected in lstAvailableCol

相关标签:
9条回答
  • 2020-11-29 12:46

    Maybe this is what you need

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        while(listBox1.SelectedIndex!=-1)
        {
               listBox1.Items.Remove(listBox1.SelectedItem);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 12:50

    You cannot modify a collection you are iterating on. In general, a good solution for this type of problem is to create an empty collection, and in your iterator, copy over all of the elements you do NOT want to remove; after the iteration is complete, replace the original collection with your new collection.

    0 讨论(0)
  • 2020-11-29 12:53

    You cannot modify an collection while you are using an Enumerator for this collection, what the for each statement does.

    You have to loop over the data with a normal for loop and then you can modify the collection, but you must be careful to correctly update the current index if you insert or remove elements. If you just add or remove elements and don't insert some, iterating from the last element to the first will do.

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        for (Int32 i = lstAvailableColors.Items.Count; i >= 0; i--)
        {
            ListItem item = lstAvailableColors.Items[i];
    
            if (item.Selected)
            {
                lstSelectedColors.Items.Add(item);
                lstAvailableColors.Items.Remove(item);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-29 12:53

    As the other answer mentioned, you can't remove items until you've completed the iteration. So perhaps something like this will be cleanest for you:

    var itemsToRemove =
    lstAvailableColors.Items.Cast<ListItem>().Where(i => i.IsSelected).ToArray();
    
    foreach(ListItem item in itemsToRemove) lstAvailableColors.Remove(item);
    
    0 讨论(0)
  • 2020-11-29 12:53

    Example on how to remove the selected Items. Here only the selected indices are taken and removed.

       public void RemoveSelectedItems(ListBox listbox)
       {
           List<ListItem> items = GetSelectedItems(listbox);
           foreach (var listItem in items)
           {
               listbox.Items.Remove(listItem);
           }
       }
    
      public List<ListItem> GetSelectedItems(ListBox listbox)
      {
         int[] selectedIndices = listbox.GetSelectedIndices();
         return selectedIndices.Select(index => listbox.Items[index]).ToList();
      }
    
    0 讨论(0)
  • 2020-11-29 12:56

    You can't modify a collection while you're iterating over it. Either iterate over a copy or use for, iterate in reverse and remove as you go down.

    0 讨论(0)
提交回复
热议问题