0

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 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.

Tom Broad
  • 82
  • 1
  • 11

1 Answers1

3

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);
       }
  }
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
  • I think this is kind of what im trying to do with the SaveValues method. I could persist the control into viewstate but the line in the foreach never gets hit. I saw someone do foreach(UserControl...) but that gave me cast exceptions. – Tom Broad Mar 25 '11 at 17:21
  • re: update - This looks pretty much exactly what I am trying to do. I read that article but was struggling to put two and two together. I need it to recreate the viewstate for the added controls (user data might not be persisted at this stage), could I stash the whole passenger object in the viewstate or is that a bit much? – Tom Broad Mar 30 '11 at 00:05
  • 1
    Fixed! @RichardFriend, Thanks for pointing me in the right direction. It was down to not recreating the controls. I had to do something a little different and ended up using this control which can persist the dynamic elements and viewstate automagically: [link](http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx) – Tom Broad Mar 30 '11 at 03:00