Ewout
Ewout

Reputation: 198

Open a Form in a Panel from a Form inside that Panel

I want to open a form inside a panel, but I want to open that form from a form that is already inside that panel. example: the name of my panel is panel and I have 3 forms, form1, form2, form3.

panel.Controls.Clear();
form2 myForm = new form2();
myForm.FormBorderStyle = FormBorderStyle.None;
myForm.TopLevel = false;
myForm.AutoScroll = true;
panel.Controls.Add(myForm);
myForm.Show();

now I want to open form3 with a button inside form2

private void button_Click(object sender, EventArgs e){
    form3 myForm = new form3();
    myForm.FormBorderStyle = FormBorderStyle.None;
    myForm.TopLevel = false;
    myForm.AutoScroll = true;
    panel.Controls.Add(myForm);
    myForm.Show();
    this.close();
}

so how do I add a new form to a panel inside a other form and close the current one

Upvotes: 2

Views: 9016

Answers (1)

LarsTech
LarsTech

Reputation: 81610

Dispose of everything that's in your panel first and don't call this.Close(); (that will close your current form):

private void button_Click(object sender, EventArgs e){
  Panel p = this.Parent as Panel;

  if (p != null) {
    while (panel.Controls.Count > 0) {
      panel.Controls[0].Dispose();
    }

    form3 myForm = new form3();
    myForm.FormBorderStyle = FormBorderStyle.None;
    myForm.TopLevel = false;
    myForm.AutoScroll = true;
    panel.Controls.Add(myForm);
    myForm.Show();
    // this.Close();
  }
}

Calling panel.Clear(); does not dispose of the controls, and can be a memory leak if you keep adding and clearing forms and controls without ever disposing them.

Edit:

After re-reading your question again, you need to reference the parent property to get the current panel:

Panel p = this.Parent as Panel;
if (p != null) {
  form3 myForm = new form3();
  myForm.FormBorderStyle = FormBorderStyle.None;
  myForm.TopLevel = false;
  myForm.AutoScroll = true;
  p.Controls.Add(myForm);
  myForm.Show();
  this.Close();
}

In this case, yes, you can call this.Close() from Form2 because that will only close that form.

Upvotes: 4

Related Questions