How can I Dynamically add (unknown type) controls to a form?
c#, controls, winforms
Solution
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());
}
Problem
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?