I added a couple of forms to a panel. The forms have the properties
form.TopLevel = false;
form.Parent = pnlMain;
Now I want to iterate through all forms in pnlMain and close all forms. To do that I have the following code:
private void CloseForms()
{
foreach(Form form in pnlMain.Controls.OfType<Form>())
form.Close();
}
My problem is, that not all forms are closed.
In an example with four open forms: I counted the open forms,
int count = pnlMain.Controls.OfType<Form>().Count();
When I call CloseForms, only two forms are closed. The other two are closed on another call at CloseForms.
How can I close all forms with only one call?
Don’t modify the collection while iterating on it. Try this