I have 3 forms MainForm, Child1 and Child2 . MainForm is the mdi container. At runtime child 1 is automatically loaded inside the MainForm. I am trying to open the form child2 from a button on child1 but i cannot seem to do it. I did everything i could. Please help.
I tried using the hide show and activate methods but nothing worked. The child1 and child2 forms are separately built.
public partial class Form1 : Form
{
public child1 c1;
public child2 c2;
public void LoadChild2()
{
if (c2 == null)
{
c2 = new child2() ;
c2.MdiParent = this;
c2.FormClosed += c2_FormClosed;
c2.FormBorderStyle = FormBorderStyle.None;
c2.Dock = DockStyle.Fill;
c2.Show();
}
else { c2.Activate(); }
}
void c2_FormClosed(object sender, FormClosedEventArgs e)
{
c2 = null;
}
public void LoadChild1()
{
if (c1 == null)
{
c1 = new child1();
c1.MdiParent = this;
c1.FormClosed += c1_FormClosed;
c1.FormBorderStyle = FormBorderStyle.None;
c1.Dock = DockStyle.Fill;
c1.Show();
}
else { c1.Activate(); }
}
void c1_FormClosed(object sender, FormClosedEventArgs e)
{
c1 = null;
//throw new NotImplementedException();
}
public Form1()
{
InitializeComponent();
LoadChild1();
// c2 = new child2();
// c1 = new child1();
// c2.MdiParent = this;
// c1.MdiParent = this;
//c1.WindowState = FormWindowState.Maximized;
// c1.FormBorderStyle = FormBorderStyle.None;
//c1.Dock = DockStyle.Fill;
// c2.FormBorderStyle = FormBorderStyle.None;
//c2.Dock = DockStyle.Fill;
// c2.Show();
// c1.Show();
//c1.Activate();
}
public partial class child1 : Form
{
//public child2 c2;
public child1()
{
InitializeComponent();
}
private void child1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
f.LoadChild2();
//child2 c2 = new child2();
//Form1 f = new Form1();
//c2.FormBorderStyle = FormBorderStyle.None;
// c2.Dock = DockStyle.Fill;
//c2.MdiParent = f;
// c2.Activate();
// c2.BringToFront();
// this.Hide();
//this.Close();
}
}
public partial class child2 : Form
{
public child2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//this.Close();
Form1 f = new Form1();
f.LoadChild1();
// child1 c1 = new child1();
// c1.FormBorderStyle = FormBorderStyle.None;
// c1.Dock = DockStyle.Fill;
// c1.Parent = f;
// c1.Show();
// c1.Activate();
}
private void child2_Load(object sender, EventArgs e)
{
}
}
Make sure to set the MdiParent
property; if spawning the new form from a Click
event handler of a button on an existing MdiChild, you can just set it to that child's MdiParent:
// Event handler inside MdiChild form (Child1)
private void spawnNewChildButton_Click(object sender, EventArgs e)
{
// Child2 is a System.Windows.Forms.Form
var child2 = new Child2() { MdiParent = MdiParent };
child2.Show();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.