首先看看效果:
動態添加,需要在PostBack之后,保留狀態,因此需要用到ViewState. 下面是簡單代碼。

顯示文本框結果:
<
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" />
這里裝載動態產生的文本框:
< 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:

private
void DymanicallyCreateTextBox()
{
TextBox tb = new TextBox();
tb.ID = " TextBox1 ";
this.PlaceHolderLoadTextBox.Controls.Add(tb);
}
{
TextBox tb = new TextBox();
tb.ID = " TextBox1 ";
this.PlaceHolderLoadTextBox.Controls.Add(tb);
}
當用戶點擊銨鈕[動態產生文本框]事件時,記得用ViewState來記錄是否有動態創建過TextBox。

protected
void ButtonDyGenerate_Click(
object sender, EventArgs e)
{
ViewState[ " Insus.NET "] = true;
DymanicallyCreateTextBox();
}
{
ViewState[ " Insus.NET "] = true;
DymanicallyCreateTextBox();
}
在Page_Load事件,去判斷ViewState是否為真。

protected
void Page_Load(
object sender, EventArgs e)
{
if (ViewState[ " Insus.NET "] != null)
DymanicallyCreateTextBox();
}
{
if (ViewState[ " Insus.NET "] != null)
DymanicallyCreateTextBox();
}
最后是獲取動態產生的TextBox,當用戶輸入值這后,點擊[獲取文本框值]銨鈕,獲取值。

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;
}
}
}
{
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;
}
}
}