我正在创建一个调查网站。我想动态添加文本框,然后在数据库中获取它们的值。
现在假设我从下拉列表中选择了 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<TextBox> 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<TextBox>)Session["AddedTextBox"];
MyTextBoxes.Add(t[j]);
Session["AddedTextBox"] = MyTextBoxes;
}
catch
{
MyTextBoxes = new List<TextBox>();
MyTextBoxes.Add(t[j]);
Session["AddedTextBox"] = MyTextBoxes;
}
}
break;
}
}
}
2) 然后在这里,我在文本框中输入值,如 a、b、c、d,然后单击“添加”:
添加点击时的点击代码:
1) 首先我在 Page_Init 上检查了 session :
protected void Page_Init(object sender, EventArgs e)
{
if (Session["AddedTextBox"] != null)
{
string a;
string b;
string c;
string d;
int listCount = ((List<TextBox>)Session["AddedTextBox"]).Count;
foreach (TextBox t in ((List<TextBox>)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 向页面动态添加控件的古老经典问题。
问题在于回发时的 View 状态和控件重建。
您需要在页面生命周期的正确时间运行生成回传控件的相同代码,以确保回传值与服务器端控件相匹配。 p>
当然,如果你想要一个 hacky 快捷方式,直接访问 Request.Form["textCheckbox"+ index]
值
关于c# - 如何使用 ASP.NET 动态创建文本框,然后将它们的值保存在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14816760/