I am still learning C# so I am sorry if I do not use the correct terminology.

Here is what I am trying to do. I have the following code that I use to check to see if an instance of a form already exists, and if it does show it. Otherwise it creates the form and then shows it.

private void btnAdd_Click(object sender, EventArgs e)
        {
            if (chbDetail.Checked == true)
            {
                bool exists = false;

                foreach (Form f in Application.OpenForms)
                {
                    if (object.ReferenceEquals(f.GetType(), typeof(Ingredient)))
                    {
                        exists = true;
                        break;
                    }
                }

                if (exists)
                {
                    Ingredient ingredient = (Ingredient)Application.OpenForms["Ingredient"];
                    ingredient.Show();
                }
                else
                {
                    Ingredient ingredient = new Ingredient();
                    ingredient.Show();
                }
            }
        }

The problem is that I need to do this with multiple forms in different parts of my program, so I wanted to create a class that I could just pass a variable into and have it open any form I wanted. I thought about using a switch but then I am still writing the code out multiple times. Any ideas would be appreciated.

Recommended Answers

All 2 Replies

Below is a method that creates a form by using its type (provided that the form has a public default constructor).
This should help you develop a more general method to show a form by passing the type of the form to open.

public Form CreateForm(Type formType)
{
    Form form = type.GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]) as Form;
    return form;
}

Thanks. That helped point me in the right direction. Here is what I ended up using.

public static void FormState(string formNamePass, Type formTypePass)
        {
            bool exists = false;
            string formName = formNamePass;
            Type formType = formTypePass;            

            foreach (Form f in Application.OpenForms)
            {
                if (object.ReferenceEquals(f.GetType(), formType))
                {
                    exists = true;
                    break;
                }
            }

            if (exists)
            {
                Form form = (Form)Application.OpenForms[formName];
                form.Show();
            }
            else
            {
                Form form = formType.GetConstructor(System.Type.EmptyTypes).Invoke(new object[0]) as Form;
                form.Show();
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.