Adding controls dynamically to an UpdatePanel in ASP.NET AJAX

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

I have the following really simple code






        
2条回答
  •  温柔的废话
    2020-12-01 09:03

    In asp.net, the controls in the ASPX file are automatically generated on each postback. The controls you've created are not in the ASPX code so the framework does not create them for you. The first time you execute the Button1_Click method, you add one extra control to the page. The second time you execute the Button1_Click method, you're on another post back and that first extra button has been forgotten about. So the result of that postback is you get one extra button again.

    This will create one extra control each time you click the button (although the timestamps will update each time you press the button because the controls are being re-created)

    protected void Button1_Click(object sender, EventArgs e)
    {
        int count = 0;
    
        if (ViewState["ButtonCount"] != null)
        {
            count = (int)ViewState["ButtonCount"];
        }
    
        count++;
        ViewState["ButtonCount"] = count;
    
        for (int i = 0; i < count; i++)
        {
            Literal literal = new Literal();
            literal.Text = DateTime.Now.ToString();
            literal.ID = DateTime.Now.Ticks.ToString();
    
            UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
            PlaceHolder1.Controls.Add(literal);
        }            
    }
    

提交回复
热议问题