How to create a control instance dynamicly by text.

  • Thread starter Jelle van Baardewijk
  • 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
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top