fawad
fawad

Reputation: 1353

Show this form from within new form instance

I have created two forms in C# using "Add new item". Form1 is my default opening form. I'm using the following code to switch to form2:

Form1 class:
    Form form2= new form2();
                this.Hide();
                form2.Show();  



Form2 class:

what should i do here to open the same form1 again without creating the new instant of form1?

Upvotes: 2

Views: 508

Answers (4)

Alan
Alan

Reputation: 6689

A simple solution could be showing the second form modally, then making the first form visible when the second form closes, like this:

  public partial class Form1: Form
  {
    public Form1()
    {
      InitializeComponent();
    }

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

  public partial class Form2: Form
  {
    public Form2()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      Close();
    }
  }

Making this work non-modally is left as an exercise :)

Upvotes: 2

vaibhav
vaibhav

Reputation: 1026

In the form2 code behind, add parameter in constructor

Form2(Form form1)
{
   //use form1 object here
   //you can declare a variable of Form1 in Form2 and use it everywhere in the scope of form2
}

Then while initialising object of form2:

Form form2 = new Form(this);
this.Hide();
form2.show();

Upvotes: 1

Vinod
Vinod

Reputation: 4892

When you are doing form2.hide() you are actually hiding not destroying it so the instance you have created still exist so you can use to show it again

if you use form2.dispose() then you have to create a new instance

Upvotes: 1

robrich
robrich

Reputation: 13205

You should pass an instance of this to form2 and have it .Show() it when the time comes.

Upvotes: 3

Related Questions