Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a control to a list of Controls dynamically

I have a web page where users need to enter customer contact information. They could enter from 0 to an infinite number of contacts.

I created this page code on page:

<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<asp:PlaceHolder ID="phCustomerContacts" runat="server" EnableViewState="true">/asp:PlaceHolder>
<asp:LinkButton ID="btnAddContact" runat="server" OnClick="btnAddContact_Click" CssClass="LinkButton" Text="Add Contact"/>

In my code behind I added this:

   public void btnAddContact_Click(object sender, EventArgs e)
    {
        IList<CustomerContactProfile> customerContacts = new List<CustomerContactProfile>();
        if (ViewState["CustomerContactList"] != null)
            customerContacts = (List<CustomerContactProfile>)ViewState["CustomerContactList"];
        CustomerContactProfile contactProfile = (CustomerContactProfile)LoadControl("~/Controls/Embedded/CustomerContactProfile.ascx");
        customerContacts.Add(contactProfile);

        foreach (CustomerContactProfile contact in customerContacts)
            phCustomerContacts.Controls.Add(contact);

        ViewState["CustomerContactList"] = customerContacts;
    }

This code doesn't work because the ViewState can't handle storing all of that control data. However, I cannot think of another way to store the controls that were already added.

The viewstate of the asp:PlaceHolder control doesn't save anything and I need the controls to be saved so that if a user puts in some data to the first control that the data isn't lost when they add a second one and so on.

like image 352
Ben Hoffman Avatar asked Feb 07 '11 13:02

Ben Hoffman


People also ask

What are dynamic controls?

Dynamic control is a method to use model predictions to plan an optimized future trajectory for time-varying systems. It is often referred to as Model Predictive Control (MPC) or Dynamic Optimization.

Which event is used to generate controls dynamically?

Retaining the dynamic controls on PostBack In order to retain the dynamic TextBoxes across PostBacks, we need to make use of Page's PreInit event to recreate the dynamic TextBoxes using the Request.


1 Answers

Rather than store the entire control, simply store the underlying data in session, and rebuild the control set from that data every time you reload the page.

like image 59
James King Avatar answered Oct 15 '22 22:10

James King