user1108948
user1108948

Reputation:

Open an existing form from the main form

I designed two forms: Form1 and Form2. Form1 is the main form. There is a button in Form1, if I click the button, then Form2 will pop out. I want to do something on Form2.

// click button in Form1.
private void button1_Click(object sender, EventArgs e)
    {
        Form form2= new Form();
        form2.ShowDialog();
    }

But Form2 is a new form rather than an existing form.

It is wrong.

How? Thanks.

Upvotes: 3

Views: 24381

Answers (5)

KaizenLouie
KaizenLouie

Reputation: 52

The question is "Open an existing form from the main form"

Okay lets change it a little, Open an existing instance of form from the main form.

when you show a form

new Form2().Show();

lets say you hid it using

Form2.Hide();

you guys can use this

var Form2_instance = Application.OpenForms.OfType<Form2>().Single();
Form2_instance.Show();

Upvotes: 0

Shefat
Shefat

Reputation: 1

 private void button1_Click(object sender, EventArgs e)
        {
            InputForm form1 = new InputForm();
            form1.Show();
        }

Here InputForm means which form you want to open.

Upvotes: 0

Tigran
Tigran

Reputation: 62265

Declare

Form2 form2= new Form2();

like your class member and use it like this:

private void button1_Click(object sender, EventArgs e)
{

        form2.ShowDialog(); //blocking call 

       //or form2.Show() //non blocking call
}

EDIT

Based on correct comments, to make this work instead of executing the Close() on the function which will lead to Dispose() you need to use form2.Hide() to make is simply invisible

Upvotes: 0

Adil
Adil

Reputation: 148180

You are creating instance of Form class not the Form2 which you have in your project. Create instance of Form2 which you created earlier and then call ShowDialog in it.

You might have notice the in the program.cs something like Application.Run(new Form1()); Here we create the instance of Form1 and pass to Run method.

Do it this way by creating instance of Form2 and calling ShowDialog() method to show it

Form2 form2= new Form2();
form2.ShowDialog();

Upvotes: 6

igofed
igofed

Reputation: 1442

You create blank form with

Form Form2= new Form();

You should use

Form2 form2= new Form2();

Complete code:

private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2= new Form2();
        form2.ShowDialog();
    }

Upvotes: 0

Related Questions