views:

114

answers:

2

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?

+4  A: 

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());
}
Lee
this is so cool, I am gonna cry! thxs
Luiscencio
+1 for the generic version. This will work fine as long as OP does not care about any functionality other than what the Control base offers.
Dynami Le Savard
+1  A: 

This would certainly work

void addcontrol(Control ctl)
{
    this.Controls.Add(ctl);            
}

private void btnNewControl_Click(object sender, EventArgs e)
{
    addcontrol(new Button());
}
John Knoeller
this is good but WHAT IF you want to check if a contol of that type already exists BEEFORE creating a new one?
Luiscencio
You are allowed to have multiple controls of the same type in a form.
John Knoeller
yeah but it will use memory that can be used in many, many, awesome things.
Luiscencio