Search code examples
c#mdichildmdiparent

show all child forms through a method


I have a mdi form and there are so many child forms on the main menu, and I use such code to open child:

        frmCustomers yeni = new frmCustomers();
        if (GenelIslemler.formAuthCheck(yeni.Name.ToString()))
        {
            if (!IsOpen(yeni.Name.ToString()))
            {
                yeni.MdiParent = this;
                yeni.WindowState = FormWindowState.Maximized;
                yeni.Show();

            }
        }
        else
        {
            MessageBox.Show("You dont have rights to access!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

but I want to write a method and just call form to that method like

openForm(frmCustomers);

and openForm method should be like this

openForm(Form frm) {...}

how can I do?


Solution

  • This is work for the reflection system built into every NET application

    using System.Reflection;
    
    private void openForm(string formName)
    {
        // First check if this form is authorized 
        if (GenelIslemler.formAuthCheck(formName))
        {
            // Then check if is already opened
            if (!IsOpen(formName))
            {
                // And now transform that string variable in the actual form to open
    
                // This is the critical line. You need the fully qualified form name. 
                // namespace + classname 
                Type formType = Type.GetType ("RapunzoApps.ThisApp." + formName);
                ConstructorInfo ctorInfo = formType.GetConstructor(Type.EmptyTypes);
                Form theForm = (Form) ctorInfo.Invoke (null);
                theForm.MdiParent = this;
                theForm.WindowState = FormWindowState.Maximized;
                theForm.Show();
            }
        }
        else
        {
            MessageBox.Show("You dont have rights to access!", "uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }