Question "Collection was modified; enumeration operation may not execute" - Help

DangerRanger89

New member
Joined
Apr 5, 2011
Messages
3
Programming Experience
Beginner
I've looked around at other forums and have seen that this is thrown because I am adding items to a collection in a for each statement. If I understand that right, I need a different way to populate my combobox here's the code.

Private Sub ShaftLoad()
Dim shaftlist As New List(Of Shaft)
shaftlist = DBShaft.GetShaftList

For Each Shaft In shaftlist
ShaftComboBox.Items.Add(Shaft.ShaftName)
Next
End Sub

This gets a list of all of the Shafts in the DB. I only need the name of the Shafts to be loaded into the combobox.

What can I do to accomplish this without modifying the collection?
 
Last edited:
Just bind the list:
VB.NET:
ShaftComboBox.DisplayMember = "ShaftName"
ShaftComboBox.DataSource = shaftlist
By the way, don't create objects that you aren't going to use. In this code:
VB.NET:
Dim shaftlist As [B][U]New List[/U][/B](Of Shaft)
shaftlist = DBShaft.GetShaftList
you create a new List object and then simply discard it as it is replaced by the List returned by GetShaftList. The 'New' keyword creates a new object. If you don't want a new object then don't use the 'New' keyword. Your should just be:
VB.NET:
Dim shaftlist As List(Of Shaft)
shaftlist = DBShaft.GetShaftList
or, more sensibly:
VB.NET:
Dim shaftlist As List(Of Shaft) = DBShaft.GetShaftList
 
Thanks

Awesome, I will definitely use binding instead of the loop. I'm still fairly new, forgive my ignorance.

I'm ashamed to say that the problem wasn't with adding objects to the combobox at all.
I was using some line shapes in my code and didn't dispose of them when the form closed. :/

You definitely taught me something though and I appreciate your time.
 
I did wonder how that code could have caused that exception because you aren't actually modifying the collection you're enumerating. All's well that ends well I guess.
 
Back
Top