Search code examples
c#asp.netcontrolspaneldynamic-data

Dynamically creation of controls in asp.net c#


I have 10 asp:Panel's that include a fieldset with asp:labels and asp:textboxes in order to retrieve the data of contact details for a company. I would like to add and delete panels(contact details fieldset) and I have followed the following approach to solve my problem.

At the beginning I have these 10 panels, and only 1 panel is Visible, the remaining 9 are InVisible. When the user desires to add a new contact the following panel changes to Visible = true. Same approach is followed for the deletion of this particular panel(contact details fieldset), I put the particular panel.Visible = false and all its fields clear.

Since the company is able to retrieve for maximum 10 contacts (their details - translate to 10 panels), my problem arises when the user desires after a while to add a new panel after deletion.

For example, the user adds Panel 1 - Panel 2 - Panel 3 for three contacts. Then he deletes Panel 1 and thereafter he desires to add another Panel. Then my program finds how many panels are available yet (visible= false) in order to create the next Panel ( since max Panels = 10), however based on the above scenario my program creates Panel 1 again at the same position like the page load ( to wit above Panel 2), but if Panel 4 is the following available will create it down of Panel 3 and this causes confusion to the user. The new Panel is created above or down of the last Panel depending on the rest of available panels (if the number of following panel is smaller or bigger of the last).

How can I fix my problem or am I following a completely wrong approach? I tried to use JavaScript to add new controls but I found many difficulties to recognize the IDs of each controller in order to store the data to my Database.


Solution

  • Instead of creating panel in the ASPX page you may create your panels and other controls in the code behind and then you can add them on the page from code. (This way you may add more than 10 panels if required)

    In Code behind.

    Panel panel1 = new Panel();
    panel1.Controls.Add(yourLabel); // add your dynamically created controls
    this.Page.Controls.Add(panel1); // add the panel to your page
    

    Or you can create a user control with panel and other controls, load the control from the code and add them on the page. For user control you may look at the following resources.

    ASP.NET User Controls - MSDN
    User controls in ASP .NET - CodeProject