如何使用ASP.NET动态创建文本框,然后将其值保存在数据库中?

我正在创建一个调查网站。 我想动态添加文本框,然后在数据库中获取它们的值。

现在让我们说我从下拉列表中选择4个动态文本框。

选择下拉列表的代码:

protected void NumDropDown_SelectedIndexChanged(object sender, EventArgs e) { if (DropDownList1.SelectedValue == "TextBox") { int j; i = int.Parse(NumDropDown.SelectedValue); Session["i"] = i; switch (i) { case 1: t = new TextBox[i]; Session["textBox"] = t; for (j = 0; j < i; j++) { t[j] = new TextBox(); t[j].ID = "txtCheckbox" + j.ToString(); Panel1.Controls.Add(t[j]); } break; case 2: t = new TextBox[i]; Session["textBox"] = t; for (j = 0; j < i; j++) { t[j] = new TextBox(); t[j].ID = "txtCheckbox" + j.ToString(); Panel1.Controls.Add(t[j]); } break; case 3: t = new TextBox[i]; Session["textBox"] = t; for (j = 0; j < i; j++) { t[j] = new TextBox(); t[j].ID = "txtCheckbox" + j.ToString(); Panel1.Controls.Add(t[j]); } break; case 4: t = new TextBox[i]; List MyTextBoxes; for (j = 0; j < i; j++) { t[j] = new TextBox(); t[j].ID = "txtCheckbox" + j.ToString(); Panel1.Controls.Add(t[j]); try { MyTextBoxes = (List)Session["AddedTextBox"]; MyTextBoxes.Add(t[j]); Session["AddedTextBox"] = MyTextBoxes; } catch { MyTextBoxes = new List(); MyTextBoxes.Add(t[j]); Session["AddedTextBox"] = MyTextBoxes; } } break; } } } 

2)然后在这里我输入textBox中的值,如a,b,c,d,然后单击ADD:

单击代码在ADD上单击:

1)首先,我在Page_Init上检查了会话:

  protected void Page_Init(object sender, EventArgs e) { if (Session["AddedTextBox"] != null) { string a; string b; string c; string d; int listCount = ((List)Session["AddedTextBox"]).Count; foreach (TextBox t in ((List)Session["AddedTextBox"])) { if (listCount == 1) { } if (listCount == 2) { } if (listCount == 3) { } if (listCount == 4) { if (t.ID == "txtCheckbox0") { a = t.Text; } if (t.ID == "txtCheckbox0") { b = t.Text; } if (t.ID == "txtCheckbox0") { c = t.Text; } if (t.ID == "txtCheckbox0") { d = t.Text; } } } } 

但这里的问题是我没有得到文本值,它们似乎是空的。 请帮我解决这个问题。

这听起来像是一个古老的经典问题,asp.net动态地向页面添加控件。

问题是在回发上使用viewstate和重建控件。

您需要在页面生命周期中的正确时间运行生成回发控件的相同代码,以确保回发值与服务器端控件匹配。

当然,如果你想要一个hacky快捷方式,直接访问Request.Form["textCheckbox" + index]

关于这个主题的有用文章。

正如提到的@ jenson-button-event,您可以通过Request.Form访问TextBox值,这是一个例子:

ASPX:

     

代码背后:

  protected void Add(object sender, EventArgs e) { int numOfTxt = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value); var table = new Table(); for (int i = 0; i < numOfTxt; i++) { var row = new TableRow(); var cell = new TableCell(); TextBox textbox = new TextBox(); textbox.ID = "Textbox" + i; textbox.Width = new Unit(180); cell.Controls.Add(textbox); row.Cells.Add(cell); table.Rows.Add(row); } container.Controls.AddAt(0,table); container.Visible = true; } protected void Submit(object sender, EventArgs e) { var textboxValues = new List(); if (Request.Form.HasKeys()) { Request.Form.AllKeys.Where(i => i.Contains("Textbox")).ToList().ForEach(i => { textboxValues.Add(Request.Form[i]); }); } //Do something with the textbox values textboxValues.ForEach(i => Response.Write(i + "
")); container.Visible = false; }