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

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

    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().Where(i => i.IsSelected).ToArray();
    
    foreach(ListItem item in itemsToRemove) lstAvailableColors.Remove(item);
    

提交回复
热议问题