积极答复者
关于Panel的Controls问题

问题
-
在后台动态的像Panel.Controls.Add(WebControl)进去,已知该WebControl是一个Table控件,然后页面上有一个Button,当点击Button后触发服务器回发事件,在该事件中使用Table tab = Panel.FindControl("TableID") as Table;去寻找该Table控件,无法找到~
进行调试跟踪获得一个奇怪现象:在执行Panel.Controls.Add(WebControl);代码的时候,Panel.Controls.Count > 1,而在按钮回发事件中,Panel.Controls.Count = 0了,怎么会这样呢?2009年10月7日 2:47
答案
-
你可以在Init里做。例子
<%@ Page Language="C#" EnableViewState="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> TextBox b; protected void Page_Init(object sender, EventArgs e) { b = new TextBox(); b.ID = "b1"; b.Text = "ok"; b.EnableViewState = true; this.Panel1.Controls.Add(b); } protected void Button1_Click(object sender, EventArgs e) { TextBox b = this.Panel1.FindControl("b1") as TextBox; Response.Write(b.Text); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </form> </body> </html>
另外,动态添加的控件不会保存状态的,你需要自己处理
【孟子E章】- 已标记为答案 科学怪人 2009年10月7日 4:22
2009年10月7日 3:45版主
全部回复
-
我刚才试了实验 你把IsPostBack去掉就可以了
protected void Page_Load(object sender, EventArgs e)
{
Label l = new Label();
l.Text = "11";
l.ID = "t";
Panel1.Controls.Add(l);
}protected void Button1_Click(object sender, EventArgs e)
{
Response.Write((Panel1.FindControl("t") as Label).Text);
}2009年10月7日 3:27 -
你可以在Init里做。例子
<%@ Page Language="C#" EnableViewState="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> TextBox b; protected void Page_Init(object sender, EventArgs e) { b = new TextBox(); b.ID = "b1"; b.Text = "ok"; b.EnableViewState = true; this.Panel1.Controls.Add(b); } protected void Button1_Click(object sender, EventArgs e) { TextBox b = this.Panel1.FindControl("b1") as TextBox; Response.Write(b.Text); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </form> </body> </html>
另外,动态添加的控件不会保存状态的,你需要自己处理
【孟子E章】- 已标记为答案 科学怪人 2009年10月7日 4:22
2009年10月7日 3:45版主