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

后端 未结 9 649
抹茶落季
抹茶落季 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:53

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

       public void RemoveSelectedItems(ListBox listbox)
       {
           List items = GetSelectedItems(listbox);
           foreach (var listItem in items)
           {
               listbox.Items.Remove(listItem);
           }
       }
    
      public List GetSelectedItems(ListBox listbox)
      {
         int[] selectedIndices = listbox.GetSelectedIndices();
         return selectedIndices.Select(index => listbox.Items[index]).ToList();
      }
    

提交回复
热议问题