Visual C # code to load Form1 again

In my Visual C # program, I have 2 call forms Form1

and Form2

.

Form1

has a button call btnfrm1

and Form2

has a button call btnfrm2

.

I need my program: -

When I press the button btnfrm1

, you need to open Form2

and hide Form1

, and when I push the button btnfrm2

, he must again show Form1

and close Form2

.

What I have coded for the click event btnfrm1

is

Form2 frm2= new Form2();
frm2.Show();
this.Hide();

      

But I don't know what to write to the Form2 btnfrm2

click event so that Form2 disappears and Form1 reappears.

Can anyone help me? any help i appreciate

+3


source to share


3 answers


Try following code



Form1 frm1 = (Form1)Application.OpenForms["Form1"];
frm1.Show();
this.Close();

      

+2


source


You really need to take a look at MdiParent

, this will create the parent application. Then all child forms will appear on the parent. So, in your initial, form

you do the following:

  • MdiContainer

    should be set to true

    .

It will be linked to MenuStrip

to work like a traditional application:



Child form = new Child();
form.Parent = this;
form.ShowDialog();

      

This is how you can do it. If you do your own approach, you should use Close

, not Hide

in such a way that it will automatically Close

and allow you to reopen. You can go for this answer which I did go into a lot in detail , just ignore the second part about tree structure.

+1


source


Your secondary form needs to know about your primary form.

public class Form1
{
    private Form2 _form2;

    public void ShowForm2()
    {
        if(_form2 == null)
        {
            _form2 = new Form2();
            _form2.Bind(this);
        }
        this.Hide();
        _form2.Show();
    }
}

public class Form2
{
    private Form1 _form1;

    public void Bind(Form1 form1)
    {
        _form1 = form1;
    }

    public void ShowForm1()
    {
        this.Hide();
        _form1.Show();
    }
}

      

+1


source







All Articles