PeterJ
PeterJ

Reputation: 373

How do I open a form in a method if passed its name as a parameter

I am trying to create a standard method to open a form based on the parameter passed to it. Basically, to get this done:

using (Quotes newQte = new Quotes())
{
    newQte.ShowDialog();
}

by replacing:

Quotes with a passed parameter, e.g. FormToOpen.

Is this at all possible?

Upvotes: 3

Views: 627

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109547

It is possible using a "Factory Method" to do so.

You would define FormToOpen like this (I'm renaming it to createForm() for clarity):

Func<Form> createForm;

So the code would look something like this:

private void MakeAndDisplayForm(Func<Form> createForm)
{
    using (var form = createForm())
    {
        form.ShowDialog();
    }
}

You would call it like this:

MakeAndDisplayForm(() => new MyForm());

Where MyForm is the type of form that you want MakeAndDisplayForm() to create.

It's fairly common to do this kind of thing; often you pass the creator function to the constructor of a class. Then that class uses the creator function later on to create things that it can use, without knowing how they were created.

This is a form of Depencency Injection.

(Disclaimer: All error checking elided for brevity)

Upvotes: 4

O. R. Mapper
O. R. Mapper

Reputation: 20722

Create a method that creates the form you want to display, based on a parameter:

public static Form CreateAppropriateForm(int formToOpen)
{
    switch (formToOpen) {
        case 0:
            return new Quotes();
        case 1:
            return new Citations();
        case 2:
            return new References();
        default:
            throw new ArgumentException("Invalid parameter value.");
    }
}

Where Quotes, Citations and References would be your form classes, derived from Form.

Then, you could invoke that method when you want to show your form:

using (Form form = CreateAppropriateForm(2)) {
    form.ShowDialog();
}

Here shown with the example of value 2 - but you are free to insert any other expression that yields a value usable for your form selection method there.

Of course, you can also declare formToOpen in a more meaningful way, if that is suitable for your application. For example, you can declare it as a custom enum type, where each enum value denotes a particular form.

Upvotes: 2

Related Questions