由于页面生命周期的关系,事先创建的空间在点击其他任何按钮后会消失,原因在于未保存状态。解决方法在Page_Load函数IsPostBack中创建与之ID相同的控件,便能保存状态。
页面代码
View Code
<div>
<asp:Button ID="BtnCreCon" runat="server" Text="Button" onclick="BtnCreCon_Click" />
<asp:Button ID="BtnShowMess" runat="server" Text="Button" onclick="BtnShowMess_Click" />
<asp:Panel ID="PCreateCon" runat="server">
</asp:Panel>
<asp:Literal ID="LtlShowMess" runat="server"></asp:Literal>
</div>
后台代码
TextBox tbx;
private int Id
{
get {
string id=Convert.ToString( ViewState["Id"]);
if (string.IsNullOrEmpty(id))
return 0;
else
return Convert.ToInt32(id);
}
set { ViewState["Id"] = value; }
}
private void CreateTextBoxListForLoad()
{
for (int i = 0; i < Id; i++)
{
tbx = new TextBox();
tbx.ID = "Tbx" + i.ToString();
PCreateCon.Controls.Add(tbx);
}
}
private void CreateTextBox()
{
tbx = new TextBox();
tbx.ID = "Tbx" + Id.ToString();
PCreateCon.Controls.Add(tbx);
}
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
CreateTextBoxListForLoad();
}
}
protected void BtnCreCon_Click(object sender, EventArgs e)
{
CreateTextBox();
Id++;
}
protected void BtnShowMess_Click(object sender, EventArgs e)
{
LtlShowMess.Text = "";
for (int i = 0; i < Id; i++)
{
LtlShowMess.Text += ((TextBox)PCreateCon.FindControl("Tbx" + i.ToString())).Text;
}
}

浙公网安备 33010602011771号