Iterate through Windows forms and close them?

五迷三道 提交于 2020-01-06 08:16:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!