Loop Error

ehelin

Freshman
Joined
Oct 11, 2005
Messages
48
Hi:

I have a wierd error that I can't seem to find out why its happening.

Problem: I am interating through a collection of combo box items. Periodically, I get the following error:

"Collection was modified; enumeration operation may not execute."

The wierd part is that I am not modifying the list (i.e. adding, removing, etc.)...or am I?

The code in question:

Dim Ctr as Integer = 0

For Each ForLpPharm As Pharmacy In cmboDefaultPharmacy.Items
If ForLpPharm.PharDBId = pMaData.PharmDbId Then
cmboDefaultPharmacy.SelectedIndex = Ctr
PharmFound = True
Exit For
End If

Ctr += 1

'Error happens here...before second interation

Next

What happens? Well, I know that the code will execute correctly once and "Ctr" will increment once to 1. The error happens after that. I also know that there are 5 items in cmboDefaultPharmacy.Items. How? Well, in an expanded version of the method with line numbers and other error trappings, I get this in the exception thrown when the error occurs.

I am unable to replicate the error in my IDE, so I can't determine the "state" of the combo box.

Thoughts?

Eric
 
Is that all the code? Which line does the exception occur on? The "Ctr += 1" line? Or the "Next"? Or something else? Does the error occur if you comment out "cmboDefaultPharmacy.SelectedIndex = Ctr"?
 
When you set the SelectedIndex, you trigger an event (SelectedIndexChanged, I think). Do you have code there?

I don't know if setting the SelectedIndex property is enough to cause the collection to change by itself. If it is, then it would violate the usage of the foreach. In that case, you can do one of two things:
1. Move the line of code that sets SelectedIndex to be outside the loop. You can check Ctr to make sure it's less than .Count and if so, set it.
2. Change the foreach to a regular For loop.

I'd probably go with #2 in this case - but I would first check if you have code in the SelectedIndexChanged event to see if that would modify the combo's items.

-ner
 
Thanks for the responses guys, but I found it...yes, it was stupid.

My boss is in to multithreading the load on all company applications...well, there was one "thread" I forgot about...opps!!!!

It was modifying the collection in question and this was causing the error...duh!!!!!

Thanks!

Eric
 
Back
Top