Search code examples
c#mdi

how to call mdi form by function


How do I create a function for 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();
        }
    }

while I want it like this

private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        CreateMdiChild(Students);
    }

and function should be like this

public void CreateMdiChild(Form form)
    {
        //expected code            
    }

Solution

  • You could make the method generic, e.g. :

    public void CreateMdiChildOrActivate<T>(ref T instance) where T : Form, new()
    {
        if (instance == null || instance.IsDisposed)
        {
            instance = new T();
            instance.MdiParent = this;
            instance.Show();
        }
        else
        {
            instance.Activate();
        }
    }
    

    Usage:

    private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        CreateMdiChildOrActivate(ref this.stu);
    }
    

    EDIT :

    If you don't want to create a class field for each form, you can do in this way:

    Create a class dictionary field containing the open form for each form-type:

    private Dictionary<Type,Form> openForms = new Dictionary<Type,Form>();
    

    Then change the previous method to:

    public void CreateMdiChildOrActivate<T>() where T : Form, new()
    {
        Form instance;
        openForms.TryGetValue(typeof(T), out instance);
        if (instance == null || instance.IsDisposed)
        {
            instance = new T();
            openForms[typeof(T)] = instance;
            instance.MdiParent = this;
            instance.Show();
        }
        else
        {
            instance.Activate();
        }
    }
    

    Now you can call it like this:

    private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        CreateMdiChildOrActivate<Student>();
    }