开发者

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

I am trying to add a user control into a div at runtime. I can add the control no p开发者_开发问答robelem but it overwrites the previous control added.

Basically, I am trying to add passengers to a travel system - the passenger details are in the user control and I don't know in advance how many there will be. I have an add new passenger button which should append the new user control into the div without overwriting the previous passenger.

The code is c#/.net 4.

I have tried to save the control data into viewstate and re add it with the new one but that also doesn't work. Here is a snippet of the code I'm using

foreach (Control uc in p_passengers.Controls) {
        Passenger p = uc as Passenger;
        if (p != null) {
            p.SaveValues();            
        }
    }

however, p.SaveAs() (just writes the control values into ViewState) is never hit.

Im sure its just something stupid but any ideas??

Cheers guys.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜