How to create a control instance dynamicly by text.

  • Thread starter Thread starter Jelle van Baardewijk
  • Start date Start date
J

Jelle van Baardewijk

Can anyone tell me how to to create a control instance dynamicly.

Example:
When I have a string value with the value 'TextBox'. I want to create a
TextBox instance.
I know that i can do the folowing: TextBox tb = new TextBox();

Now i've created a method that translates the string value:

fucntion CreateControl(string controlTypeName)
{
switch (controlTypeName)
{
case "Label":
return new Label();
case "TextBox":
return new TextBox();
}
}


but there must be a simpler way more generic way to do this.

Regards,
Jelle van Baardewijk
 
You can use this code:

Assembly assem = Assembly.GetAssembly(typeof(Form));
Type controlType = assem.GetType(controlType);
object obj = Activator.CreateInstance(controlType);
Control tb = (Control)obj;
this.Controls.Add(tb);

controlType is a string which can be System.Windows.Forms.TextBox,
ComboBox....

Good Luck
 
Back
Top