Adding controls dynamically to an UpdatePanel in ASP.NET AJAX

前端 未结 2 754
情深已故
情深已故 2020-12-01 08:42

I have the following really simple code






        
2条回答
  •  情深已故
    2020-12-01 09:02

    I agree to the answer above, However this approach will not save the state of the dynamic controls (or to be accurate, it will save the state but not load them back). Load view state is called in Load event section of page life cycle,where it assigns back the control values saved in view state. However if the controls are not created by this time, They can not be loaded with previous data so for the state to be maintained, the new controls must be recreated on or before load event.

    protected void Page_Load(object sender, EventArgs e)
    {
        //PS: Below approach saves state as id is constant, it simply generates a new control with same id hence viewstate loads the value
        if (IsPostBack)
        {
            int count = 0;
    
            if (ViewState["ButtonCount"] != null)
            {
                count = (int)ViewState["ButtonCount"];
            }
    
            count++;
            ViewState["ButtonCount"] = count;
    
            for (int i = 0; i < count; i++)
            {
                TextBox literal = new TextBox();
                //literal.Text = DateTime.Now.ToString();
                literal.ID = "Textbox" + i.ToString();
    
                //UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
                PlaceHolder1.Controls.Add(literal);
    
            }
        }
    }
    

    Dynamically adding controls View State and postback

提交回复
热议问题