C# C、 如何在foreach控制循环期间获取HTML生成的文本框值,然后显示结果?
在代码C后面,当用户选择3dropdownlist然后按下执行按钮时,它将自动生成3个文本框。在用户在3个文本框中填写姓名后,单击请求按钮,我希望用户输入的3个姓名显示在不同的结果文本框中。我该怎么做 这里是C代码C# C、 如何在foreach控制循环期间获取HTML生成的文本框值,然后显示结果?,c#,asp.net,C#,Asp.net,在代码C后面,当用户选择3dropdownlist然后按下执行按钮时,它将自动生成3个文本框。在用户在3个文本框中填写姓名后,单击请求按钮,我希望用户输入的3个姓名显示在不同的结果文本框中。我该怎么做 这里是C代码 protected void ExecuteCode_Click(object sender, EventArgs e) { int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
protected void ExecuteCode_Click(object sender, EventArgs e)
{
int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
for (int num = 1; num <= amount; num++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(t);
div1.Controls.Add(div);
}
ButtonRequest.Visible = true;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
string str = "";
foreach (Control c in phDynamicTextBox.Controls)
{
try
{
TextBox t = (TextBox)c;
// gets textbox ID property
//Response.Write(t.ID);
str = t.Text;
}
catch
{
}
}
TextBoxFinal.Text = str;
}
然后是HTML代码
<div id="div1" runat="server">
<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />
</div>
一种选择是:
创建文本框时,将Id保存在会话的列表中,然后浏览列表并使用它:
TextBox myTextbox = (TextBox)FindControl("name");
例如:
List<string> list = (List<string>)Session["myList"];
TextBox myTextbox;
foreach (string item in list)
{
myTextbox = (TextBox)FindControl(item);
//in myTextbox you have the atribute Text with the informatcion
}
对不起,我说的是英语。您无法访问在回发时动态创建的控件,但您可以尝试像这样从请求中获取输入值
protected void ExecuteCode_Click(object sender, EventArgs e)
{
List<string> tbids = new List<string>();
int amount = Convert.ToInt32(DropDownListIP.SelectedValue);
for (int num = 1; num <= amount; num++)
{
HtmlGenericControl div = new HtmlGenericControl("div");
TextBox t = new TextBox();
t.ID = "textBoxName" + num.ToString();
div.Controls.Add(t);
phDynamicTextBox.Controls.Add(div);
tbids.Add(t.ID);
}
Session["tbids"] = tbids;
ButtonRequest.Visible = true;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
string str = "";
var tbids = (List<string>)Session["tbids"];
foreach (var id in tbids)
{
try
{
str += Request[id]+" "; //here get value tb with id;
}
catch
{
}
}
TextBoxFinal.Text = str;
}
什么是不清楚的?您需要将textbox id保存在会话变量中,然后需要读取此会话并获取textbox控件的文本。告诉我你不懂什么,我向你解释我的想法:或者我把所有的都写下来code@Nacho你查过了吗-我不理解你的问题:S。我想修改问题的代码,不小心复制了你的代码。。。我就这样转身离开了。对不起@Nacho当在回发FindControl上动态添加控件时,可能会返回null@Grundy我试过了,但是我已经把代码放在了加载事件上,所以这是可行的。你说得对,谢谢。如果可能的话,不要动态创建和添加控件。使用Repeater或DataGrid从模板创建内容并将某些内容绑定到模板。这将更容易处理。