參考前一篇,http://www.cnblogs.com/insus/archive/2012/09/23/2698613.html 沒有達到用戶的要求,用戶要求是每點擊一次添加銨鈕,產生一個新的文本框TextBox,在文本框輸入一些值之后,點擊獲取文本框值的銨鈕,能取得剛才在文本框的值。首先看看修改之后的效果:
xxx.aspx:在網頁中,拉一個動態添加文本框裝載的容器PlaceHolder,和兩個銨鈕,一個是添加,另一個是獲取值。
View Code
<
asp:PlaceHolder
ID
="PlaceHolder1"
runat
="server"
></
asp:PlaceHolder
>
< br />
< asp:Button ID ="ButtonAdd" runat ="server" Text ="Add TextBox" OnClick ="ButtonAdd_Click" />
< asp:Button ID ="ButtonGetValue" runat ="server" Text ="GetTextValue" OnClick ="ButtonGetValue_Click" />
< br />
< asp:Button ID ="ButtonAdd" runat ="server" Text ="Add TextBox" OnClick ="ButtonAdd_Click" />
< asp:Button ID ="ButtonGetValue" runat ="server" Text ="GetTextValue" OnClick ="ButtonGetValue_Click" />
為了記錄添加的次數,我們需要寫一個屬性,記得點擊次數。
TotalControls
protected
int TotalControls
{
get
{
return ViewState[ " TotControls "] == null ? 0 : ( int)(ViewState[ " TotControls "]);
}
set
{
ViewState[ " TotControls "] = value;
}
}
{
get
{
return ViewState[ " TotControls "] == null ? 0 : ( int)(ViewState[ " TotControls "]);
}
set
{
ViewState[ " TotControls "] = value;
}
}
寫一個方法,動態產生文本框,方法有一個參數,就是傳入將要產生的次數。
View Code
private
void DymanicallyGenerateTextBoxControl(
int totalControls)
{
TextBox tb = new TextBox();
tb.ID = " TextBox " + totalControls;
this.PlaceHolder1.Controls.Add(tb);
}
{
TextBox tb = new TextBox();
tb.ID = " TextBox " + totalControls;
this.PlaceHolder1.Controls.Add(tb);
}
網頁一加載時,Page_Load事件中,判斷計數器為多少,循環產生文本框。
View Code
protected
void Page_Load(
object sender, EventArgs e)
{
for ( int i = 0; i < TotalControls; i++)
{
DymanicallyGenerateTextBoxControl(i + 1);
}
}
{
for ( int i = 0; i < TotalControls; i++)
{
DymanicallyGenerateTextBoxControl(i + 1);
}
}
Click事件:
View Code
protected
void ButtonAdd_Click(
object sender, EventArgs e)
{
TotalControls = TotalControls + 1;
DymanicallyGenerateTextBoxControl(TotalControls);
}
{
TotalControls = TotalControls + 1;
DymanicallyGenerateTextBoxControl(TotalControls);
}
最后是獲取文本框值的銨鈕Click事件:
View Code
protected
void ButtonGetValue_Click(
object sender, EventArgs e)
{
foreach (Control ctl in this.PlaceHolder1.Controls)
{
if (ctl is TextBox)
Response.Write(((TextBox)ctl).Text.Trim () + " <br/> ");
}
}
{
foreach (Control ctl in this.PlaceHolder1.Controls)
{
if (ctl is TextBox)
Response.Write(((TextBox)ctl).Text.Trim () + " <br/> ");
}
}

