closing a form in a panel

ssaa

New member
Joined
Jul 25, 2011
Messages
4
Programming Experience
Beginner
Iam a beginner to vb.i have a project work,related to Quotation software.i want to know how to unload all forms that are loaded on to a panel when clicking a Button.

here i did some codes, in that, one error is displaying like "Collection was modified; enumeration operation may not execute."
the code is given below:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim frm As Form
For Each frm In My.Application.OpenForms

If (frm.Name <> "additems") Then
frm.Dispose()
End If
Next
End Sub
 
The reason you get that error is that you cannot enumerate a list, i.e. loop through it with a For Each loop, and modify the list, i.e. add to it or remove from it, inside the loop. In your case, when you call Dispose you are closing the form, thereby removing it from the OpenForms collection.

What you should do is copy the items from the OpenForms collection first and then enumerate that. Closing a form will not affect your new list, so you won't get that error. The simplest option for that is a tiny bit of LINQ:
For Each f In My.Application.OpenForms.Cast(Of Form)().ToArray()
    If f IsNot Me Then
        f.Dispose()
    End If
Next
We can tighten that up in various ways:
For Each f In My.Application.OpenForms.Cast(Of Form)().Where(Function(frm) frm IsNot Me).ToArray()
    f.Dispose()
Next
Array.ForEach(My.Application.
                 OpenForms.
                 Cast(Of Form)().
                 Where(Function(f) f IsNot Me).
                 ToArray(),
              Sub(f) f.Dispose())
 
Back
Top