Adding a user control to a page programatically while preserving controls already present

前端 未结 1 1172
忘了有多久
忘了有多久 2020-12-11 14:25

I am trying to add a user control into a div at runtime. I can add the control no probelem but it overwrites the previous control added.

Basically, I am trying to ad

相关标签:
1条回答
  • 2020-12-11 14:33

    Are you re-creating all of your dynamic controls for every postback?

    Remember each postback is a new instance of the Page class and any controls you previously created will need to be explicitly re-created.

    Update

    If you had a list of added items in viewstate, something like this..

        private List<string> Items
        {
             get
             {
                  return ViewState["Items"] = (ViewState["Items"] ?? new List<string>());
             }
        }
    

    Then in your click handler you could simply add to this list :

       private void btn_Click(object sender, EventArgs e)
       {
            this.Items.Add("Another Item");
       }
    

    Then override CreateChildControls

      protected overrides CreateChildControls()
      {
           foreach (string item in this.Items)
           {
                Passanger p = new Passenger();
                p.Something = item;
                this.p_passengers.Controls.Add(p);
           }
      }
    
    0 讨论(0)
提交回复
热议问题