方法一:
要想动态添加的控件能"保持",简单的做法就是在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));
最后可以进行测试一下: