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));
}
i开发者_JAVA技巧s 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());
}
This would certainly work
void addcontrol(Control ctl)
{
this.Controls.Add(ctl);
}
private void btnNewControl_Click(object sender, EventArgs e)
{
addcontrol(new Button());
}
精彩评论