如标题中所建议的那样,我可以在其中插入多少个我想添加到占位符的文本框。我可以很好地添加文本框问题是我无法在那些动态添加的文本框中插入值。这是我的代码
这段代码的目的是每当我可以在其中引入我想要的文本框数量的文本框时。它创建并将它们添加到我页面中的占位符。
public void txtExtra_TextChanged(object sender, EventArgs e)
{
for (a = 1; a <= int.Parse(txtExtra.Text); a++)
{
TextBox txt = new TextBox();
txt.ID = "txtquestion" + a;
pholder.Controls.Add(txt);
}
}
这是提交和响应按钮的代码。写入所有这些文本框中插入的值。
protected void btnConfirm_Click(object sender, EventArgs e)
{
foreach (Control ctr in pholder.Controls)
{
if (ctr is TextBox)
{
string value = ((TextBox)ctr).Text;
Response.Write(value);
}
}
}
我一直在网上搜索,得到的答案是这段代码很好,它应该可以工作,但没有。如果你们发现任何错误或有任何可以解决我的问题的建议,我将非常感激
最佳答案
你快到了。
问题
您需要在回发时重新加载那些动态创建的文本框。否则,它们将变为空,您将无法找到它。
为此,您需要将这些动态文本框 ID 保存在持久性位置,例如 View 状态或 session 状态。
屏幕截图
ASPX
Number of TextBoxes: <asp:TextBox runat="server" ID="CounterTextBox"
OnTextChanged="CounterTextBox_TextChanged" AutoPostBack="True" /><br/>
<asp:PlaceHolder runat="server" ID="TextBoxPlaceHolder" /><br/>
<asp:Button runat="server" ID="ConfirmButton" Text="Confirm"
OnClick="ConfirmButton_Click" /><br/>
Result: <asp:Literal runat="server" ID="ResultLiteral"/>
代码隐藏
private List<string> TextBoxIdCollection
{
get
{
var collection = ViewState["TextBoxIdCollection"] as List<string>;
return collection ?? new List<string>();
}
set { ViewState["TextBoxIdCollection"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
foreach (string textboxId in TextBoxIdCollection)
{
var textbox = new TextBox {ID = textboxId};
TextBoxPlaceHolder.Controls.Add(textbox);
}
}
protected void CounterTextBox_TextChanged(object sender, EventArgs e)
{
var collection = new List<string>();
int total;
if (Int32.TryParse(CounterTextBox.Text, out total))
{
for (int i = 1; i <= total; i++)
{
var textbox = new TextBox { ID = "QuestionTextBox" + i };
// Collect this textbox id
collection.Add(textbox.ID);
TextBoxPlaceHolder.Controls.Add(textbox);
}
TextBoxIdCollection= collection;
}
}
protected void ConfirmButton_Click(object sender, EventArgs e)
{
foreach (Control ctr in TextBoxPlaceHolder.Controls)
{
if (ctr is TextBox)
{
string value = ((TextBox)ctr).Text;
ResultLiteral.Text += value;
}
}
}
关于c# - 从动态添加的文本框获取值 asp.net c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22591756/