Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Dynamically add (unknown type) controls to a form?

Hi i want to add controls to my form with a general method, something like this:

void addcontrol(Type quien)
{
    this.Controls.Add(new quien);            
}

private void btnNewControl_Click(object sender, EventArgs e)
{
    addcontrol(typeof(Button));
}

is this possible?

like image 628
Luiscencio Avatar asked Feb 27 '23 19:02

Luiscencio


1 Answers

You could create a new instance from the type instance using Activator.CreateInstance:

void AddControl(Type controlType)
{
    Control c = (Control)Activator.CreateInstance(controlType);
    this.Controls.Add(c);
}

It would be better to make a generic version:

void AddControl<T>() where T : Control, new()
{
    this.Controls.Add(new T());
}
like image 171
Lee Avatar answered Mar 23 '23 15:03

Lee