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?
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With