Creating Classes by name

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

Guest

I would lik to instantiate the appropriate control/class given its name, such
as: Control c = new Control("TextBox") this should create a new TextBox().
I can write my own code that will create the appropriate control according
to the given name using switch statement, but I'm looking for a more elegant
solution using Type class or something like that.
Thanks in advance,
Shehab.
 
Shehab Kamal said:
I would lik to instantiate the appropriate control/class given its name, such
as: Control c = new Control("TextBox") this should create a new TextBox().
I can write my own code that will create the appropriate control according
to the given name using switch statement, but I'm looking for a more elegant
solution using Type class or something like that.

Have a look at Type.GetType and Activator.CreateInstance.
 
Here is the code that worked for me:

public static Control CreateControl(string type, string name)
{
// Load the appropriate assembly from the GAC
Assembly winFormsAssembly =
Assembly.LoadWithPartialName("System.Windows.Forms");
// Get the type
Type t = winFormsAssembly.GetType("System.Windows.Forms." + type, true);
// Get a constructor with no parameters
ConstructorInfo ci = t.GetConstructor(new Type[0]);
// Invoke the constructor
Control ctrl = (Control) ci.Invoke(null);

return ctrl;
}
 
Back
Top