This error message is returned when you delete and set the selected items in ListBox.
The reason is that items are operated simultaneously when items in ListBox is traversed.
The solution is to change foreach () to items to for () to traverse item [I]
/// <Summary>
/// Set the selected items in ListBox
/// </Summary>
/// <Param name = "ListBox"> </param>
/// <Param name = "selstr"> </param>
Private Void Sellistbox (system. Windows. Forms. ListBox, String Selstr)
{
// Foreach (Object OBJ in ListBox. Items)
// {
// If (obj. tostring () = selstr)
// {
// ListBox. selecteditems. Add (OBJ );
// }
// }
For ( Int I = 0 ; I <ListBox. Items. Count; I ++)
{
If (ListBox. items [I]. tostring () = selstr)
{
ListBox. selecteditems. Add (ListBox. items [I]);
}
}
}
ListBox. clearselected method [C #]
Calling this method is equivalent to setting the selectedindex attribute to negative 1 (-1 ).
You can use this method to quickly deselect all items in the list.
Foreach (Object D in listbox2.selecteditems)
This row has a problem. When one of the options is deleted, the options of ListBox have been changed and foreach is called. Of course, there will be a problem!
For ( Int I = listbox1.items. Count- 1 ; I>- 1 ; I --)
{
If (Listbox1.getselected (I ))
{
Listbox1.items. removeat (I );
}
}
Pay attention to two points.
1. Getselected (I) gets the selected status
2. Reverse Order is required for loop traversal. Otherwise, the index changes after the option is deleted, causing an error in the sequence number to be deleted.
URL: http://greatverve.cnblogs.com/archive/2012/07/31/foreach-listbox.html