Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close Multiple forms in Windows form Application

I am working with windows form application in Visual studio 2015. Now my requirement is to close multiple windows form on button click.

Note: I referred below links

closing-multiple-forms-in-c-sharp

How-to-Connect-forms-in-Csharp-windows-application

How to swap between forms in windows forms application

Check the Below images what i have worked.

Image - 1 enter image description here

Image - 2 enter image description here

Image - 3 enter image description here

Image - 4 enter image description here

like image 277
Dinesh Reddy Alla Avatar asked May 31 '26 11:05

Dinesh Reddy Alla


2 Answers

You created another instance of your first form and hide it, so your first form which is currently open will not hide.

You should hide the open instance. To do so, you can find it using Application.OpenForms:

var first = Application.OpenForms.OfType<FirstForm>().FirstOrDefault();
if (first != null)
    first.Hide();

Also you can keep a reference to the first form in Program class and use that reference to Hide it or Show it again.

Please note, Application.OpenForms returns visible forms and if you hide a form, then the form will not present in the collection anymore.

like image 66
Reza Aghaei Avatar answered Jun 03 '26 01:06

Reza Aghaei


its simple .. when you call form2 then you have to pass reference of form1 and hide the main form and close the form2 when Click on button1 and open frmshow..

when you click on BtnAnalysis...

 private void BtnAnalysis_Click(object sender, EventArgs e)
 {
     Form2 frm2 = new Form2();
     frm2.Show(this);        // here the reference of form1 pass to the form2
 }

In Your Form2 You Have To do Code like this...

    private Form1 frm;
    public Form2()
    {
        InitializeComponent();
    }

    public void Show(Form1 frm1)
    {
        frm = frm1;      // here assign the reference of form1 to form for hiding purpose
        this.Show();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frmshow frmshw = new frmshow();
        frm.Hide();        // hide mainform i.e. form1
        this.Close();      // close the form2
        frmshw.Show();     // show the frmshow form
    }

Its Worked for sure ... you have to try this ... if you want source then Contact me by my email.[email protected]

like image 37
Er Ketan Vavadiya Avatar answered Jun 03 '26 01:06

Er Ketan Vavadiya