简体   繁体   中英

How do I dynamically add a user control based on user input?

I have a user control (.ascx) added to my application:

<uc1:pomedsrow runat="server" id="POMedsRow" />

And here is html and logic

<asp:Panel ID="Panel1" runat="server">
    How many PO Meds do you wish to order?
    <asp:TextBox ID="txtReqPONum" runat="server" />
    <asp:LinkButton ID="lbnAddPOMeds" runat="server" Text="Go" 
                    OnClick="lbnAddPOMeds_Click"/>
</asp:Panel>

<asp:Panel ID="pnlPOMeds" Visible="false" runat="server">
    <table border="1">
    <tr>
        <td><p>PO Meds</p></td>
        <td><p>Min/Max</p></td>
        <td><p>Amount to Order</p></td>
    </tr>
    <uc1:pomedsrow runat="server" id="POMedsRow" />
    </table>
    <br />
</asp:Panel> 

protected void lbnAddPOMeds_Click(object sender, EventArgs e)
{
    int ReqPO = Convert.ToInt32(txtReqPONum.Text);
    int n = ReqPO;
    for (int i = 0; i < n; i++)
    {
        Control pomedsrow = new Control();
        //Assigning the textbox ID name 
        pomedsrow.ID = "txtPOAmount" + "" + ViewState["num"] + i;
        this.Form.Controls.Add(pomedsrow);
    }

}

But when I click the link button nothing happens. Am I not calling the custom control correctly?

You are not adding your control properly. Try this:

protected void lbnAddPOMeds_Click(object sender, EventArgs e)
{
    TextBox txtReqPONum = (TextBox) Panel1.FindControl("txtReqPONum");
        int ReqPO = 0;
        if (txtReqPONum != null && int.TryParse(txtReqPONum.Text, out ReqPO) )
        {            
            int n = ReqPO;
            for (int i = 0; i < n; i++)
            {
                UserControl myControl = (UserControl)Page.LoadControl("~/pomedsrow.ascx");//(UserControl)Page.LoadControl("Your control path/pomedsrow.ascx");
                //Assigning the textbox ID name 
                myControl.ID = "txtPOAmount" + "" + ViewState["num"] + i;
                Panel1.Controls.Add(myControl);
            }
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM