[英]Generic function to create controls at runtime
I want to add controls to my aspx web form at runtime using C#. 我想在运行时使用C#将控件添加到我的aspx Web表单中。
I would like to write a generic function which will create any type of control (Eg: textbox, lable, button etc). 我想写一个通用函数,它将创建任何类型的控件(例如:文本框,标签,按钮等)。
Any ideas please. 有什么想法。 Thanks BB
谢谢BB
I suppose you could do something like this: 我想你可以做这样的事情:
public void CreateControl<W>(Func<W> controlConstructor) where W : WebControl
{
W control = controlConstructor();
//add control and configure it, etc etc
}
You can do this, as long as the control types you want to use all have a default constructor. 只要您要全部使用的控件类型都具有默认构造函数,就可以执行此操作。
T AddControl<T>() where T : WebControl, new()
{
T ctrl = new T();
...
return ctrl;
}
Add TextBoxes Control to Placeholder 将TextBoxes控件添加到占位符
private void CreateTextBoxes()
{
for (int counter = 0; counter <= NumberOfControls; counter++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + (counter + 1).ToString();
// add some dummy data to textboxes
tb.Text = "Enter Title " + counter;
phTextBoxes.Controls.Add(tb);
phTextBoxes.Controls.Add(new LiteralControl("<br/>"));
}
}
In CreateTextBoxes method I loop through 'n' numbers of controls that we wants to create dynamically in phTextBoxes placeholder. 在CreateTextBoxes方法中,我循环浏览要在phTextBoxes占位符中动态创建的n个控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.