Search code examples
c#winformsmdi

How to create a function for mdi container


How do I create a function for my following code so that i may not have to write the following whole code to make a form be used as MDICHILD Form.

Students stu = null;
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
  if (stu == null || stu.IsDisposed)
  {
    stu = new Students();
    stu.MdiParent = this;
    stu.Show();
  }
  else
  {
    stu.Activate();
  }
}

Solution

  • Try this

    private void CreateMdiChild<T>(ref T t) where T : Form, new()
    {            
        if (t == null || t.IsDisposed)
        {
            t = new T();
            t.MdiParent = this;
            t.Show();
        }
        else
        {
            if (t.WindowState == FormWindowState.Minimized)
            {
                t.WindowState = FormWindowState.Normal;
            }
            else
            {
                t.Activate();
            }
        }
    }
    

    Usage:

    Students students;
    private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        CreateMdiChild<Students>(ref students);
    }