1

I am trying to add some existing forms to a collection dynamically.

The below code will iterate through the assemblies and find any forms (hope I got that right). If a form matches part of the form name, I wanted to add it to the collection. I, of course, could do this explicitly in code by Forms.add(new frm_Form1). I wanted to do it this way so I don't forget to add a form (I guess I'm being kind of lazy).

    List<Form> Forms = new List<Form>();

    private void addForms()
    {
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

        foreach (Assembly a in assemblies)
        {
            Type[] types = a.GetTypes();

            foreach (Type t in types)
            {
                if (t.BaseType == typeof(Form))
                {
                    if (t.Name.Substring(0, 4).ToLower() == "frm_")
                    {
                        // How to add the form (found in the for loop) to the Forms collection.
                    }
                }
            }
        }
    }

Hope you can help.

Thanks

IronAces
  • 1,857
  • 1
  • 27
  • 36

1 Answers1

1

In your loop you are loking for types - not instances. When you find one, and it is your goal, you could use Activator.CreateInstance() to create an instance of your type, and than add it to your collection. Here is an example of Activator usage.

Form instance = (Form)Activator.CreateInstance(t);
Forms.Add(instance);
Jonatan Dragon
  • 4,675
  • 3
  • 30
  • 38