如何根据用户输入动态添加用户控件?

时间:2013-10-11 19:07:52

标签: c# asp.net user-controls

我在我的应用程序中添加了一个用户控件(.ascx):

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

这是html和逻辑

<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);
    }

}

但是当我点击链接按钮时没有任何反应。我没有正确调用自定义控件吗?

1 个答案:

答案 0 :(得分:0)

您没有正确添加控件。试试这个:

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);
            }
        }

}