Dynamic population of usercontrol

I have a custom usercontrol and it is a dropdownbox with a button beside it.

<asp:Panel ID="pnlSelect" runat="server">        
        <asp:Label ID="lblNameSelect" runat="server" Text="Name"></asp:Label>:&nbsp;
        <asp:DropDownList ID="ddlDivision" runat="server"></asp:DropDownList>&nbsp;
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</asp:Panel>

I need to create this during runtime.

        UserControl.UCDropDownBox drpDivision = LoadControl("~/UserControl/UCDropDownBox.ascx") as UserControl.UCDropDownBox;
        drpDivision.ID = "drp1";
        drpDivision.LabelText = "Division";
        drpDivision.DataSource = dt;
        drpDivision.DataTextField = "colDescription";
        drpDivision.DataValueField = "colValue";
        phFormContent.Controls.Add(drpDivision);

Now I want to generate the next usercontrol (same usercontrol) when the button from the first usercontrol is clicked so I can get the selectedvalue from the first usercontrol.

Answers


Wouldn't this be a LOT easier if you put your UserControl in a Repeater?

<asp:Repeater ID="multiControls" runat="server">
<ItemTemplate>
  <asp:Panel ID="pnlSelect" runat="server">        
        <asp:Label ID="lblNameSelect" runat="server" Text="Name"></asp:Label>:&nbsp;
        <asp:DropDownList ID="ddlDivision" runat="server"></asp:DropDownList>&nbsp;
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
  </asp:Panel>
</ItemTemplate>
</asp:Repeater>

You could then bind a collection of objects to the Repeater. Taking this approach, to solve your problem, all you need to do is:-

  1. Add new item to collection
  2. Re-bind Repeater

Not only does this vastly simplify the creation of new User Control objects, but it also makes loading previously persisted data a lot easier.


Need Your Help

undoing damage from wrong /etc/apt/sources.list

apt-get package-managers

I had the wrong ubuntu version listed in /etc/apt/sources.list some (it listed precise instead of trusty) which I only discovered after a full day of workarounds for packages that wouldn't install

Localize datetime (timezone aware) from timezone offset

python pytz python-dateutil python-datetime

I have a UTC timestamp and a timezone offset timestamp (both in milliseconds):