方法一:
要想動態添加的控制項能"保持",簡單的做法就是在page_init裡載入,而不是page_load
C# code
protected override void OnInit(EventArgs e) { try { //在這裡載入控制項 base.OnInit(e); } catch (Exception MyEx) { MyHelper.ShowExceptionMeessage(MyEx); } finally { } }
方法二:
protected void Page_Load(object sender, EventArgs e){ if (!IsPostBack) { LoadTextBox(); }}protected override void LoadViewState(object savedState){ base.LoadViewState(savedState); if (IsDynamicLoadControl) { LoadTextBox(); }}private void LoadTextBox() { for (int i = 0; i < 10; i++) { TextBox input = new TextBox(); input.ID = "input" + i.ToString(); this.form1.Controls.Add(input); } IsDynamicLoadControl = true;}public bool IsDynamicLoadControl{ get { object dynamic = ViewState["IsDynamicLoadControl"]; return dynamic == null ? false : true; } set { ViewState["IsDynamicLoadControl"] = value; }}
TextBox tb = this.FindControl("input0") as TextBox;ClientScript.RegisterStartupScript( this.GetType(), "", string.Format("<script>alert('{0}')</script>",tb.Text));
最後可以進行測試一下: