Open an existing form from the main form

I developed two forms: Form1and Form2. Form1- the main form. In Form1there is a button, if I press the button, appears Form2. 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- this is a new form, not an existing form.

It is not right.

How? Thank.

+3
source share
4 answers

An instance of the Form class is created, not Form2, which you have in your project. Create an instance of Form2 that you created earlier, and then call ShowDialog on it.

You may have noticed something like Application.Run in the program program.cs (new Form1 ()); Here we create an instance of Form1 and move on to the Run method.

, Form2 ShowDialog(),

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

Form2 form2= new Form2();

, :

private void button1_Click(object sender, EventArgs e)
{

        form2.ShowDialog(); //blocking call 

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

EDIT

, Close() , Dispose(), form2.Hide(),

0

You create an empty form with

Form Form2= new Form();

You have to use

Form2 form2= new Form2();

Full code:

private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2= new Form2();
        form2.ShowDialog();
    }
0
source
 private void button1_Click(object sender, EventArgs e)
        {
            InputForm form1 = new InputForm();
            form1.Show();
        }

Here InputForm means which form you want to open.

0
source

All Articles