Hi Salisu Shaibu,
Your code doesn't work because you are creating a new instance of your MainForm. The trick is to use a reference to the MainForm and set it as MdiParent to your second Form. Have a look at this (runnable) example:
using System;
using System.Windows.Forms;
namespace MdiOhMy
{
static class Program
{
[STAThread]
static void Main()
{
Form formMain = new Form { IsMdiContainer = true };
Form formChild1 = new Form { Text = "Child1", MdiParent = formMain, Visible = true };
Button buttonShowChild2 = new Button { Text = "Open Child2", Parent = formChild1 };
buttonShowChild2.Click += (object sender, EventArgs e) =>
{
Form formChild2 = new Form { Text = "Child2", MdiParent = formMain, Visible = true };
};
Application.Run(formMain);
}
}
}
In this example I can reference the formMain instance because it's in the captured scope. In a more realistic Scenario you can obtain a reference via Child1's
MdiParent
property.
So your handler could look like this:
private void btnOpen_Click(object sender, EventArgs e)
{
MainForm mainForm = this.MdiParent as MainForm;
MainForm.child2 = new Child2();
MainForm.child2.MdiParent = fMainForm;
MainForm.child2.Show();
}
Also think about if you want to create a new instance of Child2 every time you click your button, or just hide/reshow the same instance...
Happy coding
Johannes