how to write a function doing this code

170 views Asked by At

I've used this code to make and show a form in a MdiWindow:

        if (currentForm != null) {
            currentForm.Dispose();
        }
        currentForm = new ManageCompanies();
        currentForm.MdiParent = this;
        currentForm.Show();
        currentForm.WindowState = FormWindowState.Maximized;

I used this code to show about 20 different forms...

I want to write a such function:

private void ShowForm(formClassName) {

            if (currentForm != null) {
                currentForm.Dispose();
            }
            currentForm = new formClassName();
            currentForm.MdiParent = this;
            currentForm.Show();
            currentForm.WindowState = FormWindowState.Maximized;
}

Do I have to send formClassName as a string or something else; and how to include it in the code... I want the final code...

2

There are 2 answers

6
Aliostad On BEST ANSWER

Try generics:

 public void ShowForm<FormClass>() where FormClass: Form,new() {

        if (currentForm != null) {
            currentForm.Dispose();
        }
        currentForm = new FormClass();
        currentForm.MdiParent = this;
        currentForm.Show();
        currentForm.WindowState = FormWindowState.Maximized;
}

Or using reflection

public void ShowForm(string formClassName) {

        if (currentForm != null) {
            currentForm.Dispose();
        }
        currentForm = (Form) Activator.CreateInstance(Type.GetType(formClassName)) ;
        currentForm.MdiParent = this;
        currentForm.Show();
        currentForm.WindowState = FormWindowState.Maximized;
}
0
James Michael Hare On

You also have to specify:

private void ShowForm<FormClass> where T : Form, new() {

Note the new() on there so you can default construct the FormClass, otherwise it won't let you construct it.