动态添加,需要在PostBack之后,保留状态,因此需要用到ViewState. 下面是简单代码。
View Code 显示文本框结果:<asp:Label ID="LabelResult" runat="server" Text=""></asp:Label><br />
这里装载动态产生的文本框:
<asp:PlaceHolder ID="PlaceHolderLoadTextBox" runat="server"></asp:PlaceHolder><br />
<asp:Button ID="ButtonDyGenerate" runat="server" Text="动态产生文本框" OnClick="ButtonDyGenerate_Click" />
<asp:Button ID="ButtonGetTextBoxValue" runat="server" Text="获取文本框值" OnClick="ButtonGetTextBoxValue_Click" />
动态产生TextBox:
DymanicallyCreateTextBox() private void DymanicallyCreateTextBox()
{
TextBox tb = new TextBox();
tb.ID = "TextBox1";
this.PlaceHolderLoadTextBox.Controls.Add(tb);
}
当用户点击铵钮[动态产生文本框]事件时,记得用ViewState来记录是否有动态创建过TextBox。
View Code protected void ButtonDyGenerate_Click(object sender, EventArgs e)
{
ViewState["Insus.NET"] = true;
DymanicallyCreateTextBox();
}
在Page_Load事件,去判断ViewState是否为真。
Page_Load protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["Insus.NET"] != null)
DymanicallyCreateTextBox();
}
最后是获取动态产生的TextBox,当用户输入值这后,点击[获取文本框值]铵钮,获取值。
ButtonGetTextBoxValue_Click protected void ButtonGetTextBoxValue_Click(object sender, EventArgs e)
{
if (ViewState["Insus.NET"] != null)
{
foreach (Control ctl in this.PlaceHolderLoadTextBox.Controls)
{
if (ctl is TextBox && ((TextBox)ctl).ID == "TextBox1")
this.LabelResult.Text = (ctl as TextBox).Text;
break;
}
}
}