Collection was modified; enumeration operation may not execute

后端 未结 16 2545
南旧
南旧 2020-11-21 06:05

I can\'t get to the bottom of this error, because when the debugger is attached, it does not seem to occur.

Collection was modified; enumeration operatio

16条回答
  •  臣服心动
    2020-11-21 06:58

    I've seen many options for this but to me this one was the best.

    ListItemCollection collection = new ListItemCollection();
            foreach (ListItem item in ListBox1.Items)
            {
                if (item.Selected)
                    collection.Add(item);
            }
    

    Then simply loop through the collection.

    Be aware that a ListItemCollection can contain duplicates. By default there is nothing preventing duplicates being added to the collection. To avoid duplicates you can do this:

    ListItemCollection collection = new ListItemCollection();
                foreach (ListItem item in ListBox1.Items)
                {
                    if (item.Selected && !collection.Contains(item))
                        collection.Add(item);
                }
    

提交回复
热议问题