InvalidOperationException on a Collection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

In teh MSDN article:

http://msdn.microsoft.com/library/d...systeminvalidoperationexceptionclasstopic.asp

regarding the InvalidOperationException class it talks about this exception
is thrown by MoveNext if objects of a collection are modified after the
enumerator is created.

I seriously do not understand this. What changes to an object would trigger
this, and what wouldnt. I can see how disposing of an object might cause a
problem, but changing data - would that, probably not. So what is the story,
what can you do about it etc.

I am getting this issue managing a set of controls. I have tried to create a
new collection and then loop through adding into the new and removing from
the old, on the basis that this might be a hammer to crack a nut. This works
in the immediate window, but not in code - interesting.

Try
Cntrls.Add(cntrl)
Catch InvOpEx As InvalidOperationException
'A complete frig to try and resolve this error
If Cntrls.Count = 0 Then
Cntrls = New Collection
Else
Dim newCntrls As New Collection
Dim o As Object
Dim i As Integer
For i = 1 To Cntrls.Count
newCntrls.Add(Cntrls(1))
Cntrls.Remove(1)
Next
Cntrls = Nothing
Cntrls = newCntrls
End If
Cntrls.Add(cntrl)
End Try
 
By the way - this code seams to work - forgot that. Just unwieldly. Tried
getting hold of the Enumerator and restting it - failed.
 
Back
Top