问题
I'm trying to use the following code to iterate over all of the currently open forms in my application and close them except for the main form as part of a clean up.
Dim openForms As Windows.Forms.FormCollection = Application.OpenForms
For Each frm As Windows.Forms.Form In openForms
If frm.Name.ToString() <> "FrmMainNew" Then
frm.Close()
End If
Next
However, I'm getting an InvalidOperationException
because when frm.Close()
is executed, the entry that was in openForms
is deleted, changing the size of the collection. I'm obviously doing something wrong, so if anyone can point me at the problem here, that would be awesome. Otherwise, is there another way to do something like this?
回答1:
Iterate backwards so that modifying the collection doesn't byte:
For ix As Integer = Application.OpenForms.Count - 1 To 0 Step -1
Dim frm = Application.OpenForms(ix)
'' etc..
Next
回答2:
Use "while" loop instead of "For", check Application.OpenForms.Count > 1 When you use while loop, you do "something" while "something else" is happening. You don't iterate trough collection and it is not mutating on you.
回答3:
Another way to do it :
For Each OFORM in Application.Openforms
With OFORM
'Methods and conditions here
End With
Next OFORM
来源:https://stackoverflow.com/questions/12940279/iterate-through-windows-forms-and-close-them