Search code examples
vb.netwinformsforeach

Iterate through Windows forms and close them?


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?


Solution

  • 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