creating instance of a form from a variable

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Ususally we do like:

SalesOrderForm fm = new SalesOrderForm();

where SalesOrderForm is a valid form in one of the assembly, that is
SalesOrderForm is a type. How can I create an instance of SalesOrderForm
when I do not know its type at run tyme? For example

public openForm (string formName)
{
// here I might get "SalesOrderForm" or something else. If I get
"SalesOrderForm" then I want to open it.
Here, it will also be NOT known which assembly this for is in.
}

Thanks.
 
You can use reflection to create an instance of any type including forms
specified at runtime (for example you might want to take a look at
Activator.CreateInstance). However, you must specify in which assembly the
framework should look for the type. How else is the framework supposed to
know where to find the type?

HTH, Jakob.
 
Harshad Rathod said:
SalesOrderForm fm = new SalesOrderForm();

where SalesOrderForm is a valid form in one of the assembly, that is
SalesOrderForm is a type. How can I create an instance of SalesOrderForm
when I do not know its type at run tyme? For example

public openForm (string formName)
{
// here I might get "SalesOrderForm" or something else. If I get
"SalesOrderForm" then I want to open it.
Here, it will also be NOT known which assembly this for is in.
}

You can use 'Activator.CreateInstance' to instantiate a type by its name.
Take a look at the overloads of this method.
 
I guess I will have to build an array of assembly-names/form-names at the
entry point and then use AssembleName.GetType(MyFormNameVariable). I wnated
to avoid building the array.

Thanks.
 
I considered that but as I mentioned, I don't have the assembly anme at the
time I wnat to trigger this.

I am going to build an array of assembly-name/form-name at the beginning of
the app.

Thanks.
 
THIS did the trick.

Form fm;
fm = (Form) Activator.CreateInstance("WinUI",
"WinUI.Framework.FmMaster").Unwrap();

Thanks everyone for help.

Harshad
 
I forgot to mention: I did not want to supply "WinUI". With that even the
following works.
fm = (Form) Assembly.Load("WinUI").CreateInstance("WinUI.Framework.FmMaster");
 
Back
Top