Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi How can I close all the forms by clicking on a button?
I want to close all the forms and open the start form.
can anyone help me?
Posted

Try as below code to close all Open Forms of your application.

C#
foreach (Form form in Application.OpenForms)
{

   form.Close();

}


EdMan196 Suggested Improvement (improved again):
C#
for (int i = Application.OpenForms.Count - 1; i != -1; i = Application.OpenForms.Count - 1) 
{ 
     Application.OpenForms[i].Close(); 
}


Edite by RaisKazi - Thanks for suggestion EdMan196. I would say below code should provide exact result.

C#
int openForms = Application.OpenForms.Count;
for (int i = 0; i < openForms; i++)
{
 Application.OpenForms[i].Close();
}
.
 
Share this answer
 
v5
Comments
Uday P.Singh 28-Aug-11 5:08am    
correct my 5
RaisKazi 28-Aug-11 5:24am    
Thanks Uday.
isooda 28-Aug-11 5:12am    
I tried above code but it has an error.and the error is
"Collection was modified; enumeration operation may not execute."
RaisKazi 28-Aug-11 5:19am    
Have a look below link to resolve this error.
http://www.codeproject.com/Answers/230414/Collection-was-modified-enumeration-operation-may-.aspx#answer2
isooda 28-Aug-11 5:20am    
I tride "Application.exit();" and it worked and all the forms were closed.
but I want to open the start form as all the forms are closed.what should I do?
help me please if you can.
This will close ALL of the forms, except the mainform (if it's already open). It also takes into account the possibility that the form that's currently running this code may NOT be the last form in the list.

C#
int baseIndex = 0;
int thisFormIndex = -1;
// close all forms except the main one and this one
while (Application.OpenForms.Count > 1)
{
    if (Application.OpenForms[baseIndex] is MainForm || Application.OpenForms[baseIndex].Equals(this))
    {
        if (Application.OpenForms[baseIndex].Equals(this))
        {
            thisFormIndex = baseIndex;
        }
        baseIndex++;
    }
    else
    {
        Application.OpenForms[baseIndex].Close();
    }
    if (Application.OpenForms.Count == 2 && thisFormIndex >= 0)
    {
        break;
    }
}
if (thisFormIndex >= 0)
{
    Application.OpenForms[thisFormIndex].Close();
}


I typed this off the top of my head, so the code may need some tweaking, but you should have an idea of what I was going for.

In the end, this is a crap design, and the desired processing should actually be handled by a combination of semaphores and events so that each preceding form can determine on its own whether or not it should close based on how the child form it's monitoring closed.

EDIT ======================

You can open the main form by simply doing this:

C#
mainForm form = new MainForm();
form.ShowDialog();


Your design still sucks. Read the last paragraph of my original answer. Read it as many times as it takes for you to understand it.
 
Share this answer
 
v6
Comments
RaisKazi 28-Aug-11 8:43am    
My 5!
isooda 28-Aug-11 10:08am    
I typed John Simmons code and all the forms were hidden but start form(main form)
wasn't opened.
#realJSOP 28-Aug-11 14:33pm    
If all the forms were closed, then the mainform wasn't open when you ran the code. Simply add a line to open the desired form. Do we really have to hold your hand on this?
Check this out:

C#
private void Button1_Click(System.Object sender, System.EventArgs e)
{
	for (int i = Application.OpenForms.Count - 1; i >= 0; i += -1)
		Application.OpenForms(i).Close();
}


If this is done by For...Each loop it raises InvalidoperationException that 'Collection was modified; enumeration operation may not execute.'
 
Share this answer
 
v3
Comments
RaisKazi 28-Aug-11 9:20am    
My 5. Have you looked at my Edited Answer?
Shahan Ayyub 28-Aug-11 9:29am    
which one RaisKazi ?
I didn't see. Is this the copied ? I have seen the very first (all pages) now but didn't find a exact solution. :S

I did this kind of work when i removed empty rows from datatable. So placed here.
RaisKazi 28-Aug-11 9:57am    
Look at the code just below "Edite by RaisKazi",also obeserve the "Last Edited" Time.
Shahan Ayyub 28-Aug-11 10:42am    
I have read the whole discussion 'now'. Didn't see the comments along with the code. But still i was thinking from different point of view regarding iteration and exception on for loop and for each loop.
A little Linq anyone ?

1. if you know for a fact that all secondary forms are instances of the same base type ... we'll call this 'OtherForm' in this example:
List<OtherForm> otherFormList = Application.OpenForms.OfType<OtherForm>().ToList();

foreach(OtherForm othrFrm in otherFormList) othrFrm .Close();

The fact we projected the Application.OpenForms collection into a new List via Linq avoids the 'modifying collection' error.

2. Now, let's consider the case where there's many possible kinds of 'secondary forms' launched, and you want to close all but the form in whose code context you are currently running
C#
List<Form> AllButThisForm = Application.OpenForms
    .OfType<Form>()
    .Where(frm => ! frm.Name.Contains(this.Name))
    .ToList<Form>();

foreach (Form othrFrm in AllButThisForm) othrFrm.Close();
Note that the test we apply in example #2 above assumes that the form we wish to remain open has a 'unique name,' and that the context in which we use the 'this' operator will return the name of the currently executing Form context.

In each case shown above, the "main form" is left open.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900