如何使用循环创建动态数量的TextBox控件?

我正在尝试动态创建TextBox 。 但它不起作用。 它给了我一个错误:

“TextBox”类型的控件“0”必须放在带有runat = server的表单标签内。

这是我的aspx代码:

  

这是我的Codebehind:

 public void show(object sender, EventArgs e) { for (int i =0; i <3; i++) { TextBox _text = new TextBox(); _text.Visible = true; _text.Text = i.ToString(); _text.ID = i.ToString(); this.Controls.Add(_text); } } 

试试这个:

 this.Form.Controls.Add(_text); 

该错误告诉您TextBox必须位于

标记内。 如果将其添加到“this”的Controls中,则会在

之后添加。

即使您将控件放在窗体控件中,您也无法在回发时检索该值。

动态控制的问题是你需要在页面的每个post上重新加载控件(具有相同的id)。

否则,它们将不在控制树中,您将无法找到它们。

这是一个样本。 它动态加载TextBox控件,并在单击“提交”按钮时显示该值。

ASPX

     

代码背后

 protected void Page_Init(object sender, EventArgs e) { if (IsPostBack) { LoadControls(); } } protected void OkButton_Click(object sender, EventArgs e) { LoadControls(); } protected void SubmitButton_Click(object sender, EventArgs e) { var myTextBox = FindControlRecursive(PlaceHolder1, "MyTextBox") as TextBox; MessageLabel.Text = myTextBox.Text; } private void LoadControls() { // Ensure that the control hasn't been added yet. if (FindControlRecursive(PlaceHolder1, "MyTextBox") == null) { var myTextBox = new TextBox {ID = "MyTextBox"}; PlaceHolder1.Controls.Add(myTextBox); } } public static Control FindControlRecursive(Control root, string id) { if (root.ID == id) return root; return root.Controls.Cast() .Select(c => FindControlRecursive(c, id)) .FirstOrDefault(c => c != null); } 

form添加控件,而不是将其添加到form

 for (int i =0; i <3; i++) { TextBox _text = new TextBox(); _text.Visible = true; _text.Text = i.ToString(); _text.ID = i.ToString(); form.Controls.Add(_text); }