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

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

    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);
            }
        }
    }
    

提交回复
热议问题