开发者

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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜