血泪

一切都是源于对你的爱~
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

动态创建控件

Posted on 2011-06-28 11:01  xiaoqiang_888  阅读(137)  评论(0)    收藏  举报

由于页面生命周期的关系,事先创建的空间在点击其他任何按钮后会消失,原因在于未保存状态。解决方法在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;
}
}