从后面的代码添加用户控件

use*_*116 4 c# asp.net jquery user-controls asp.net-4.0

我的页面上有一个用户控件(UserControl1 )和一个“添加更多”按钮。单击“添加更多”按钮再次添加相同的用户控件。当我第一次单击用户控件时,它会添加第二个用户控件,但第二次时不会添加其他。我认为控制丢失了。我在链接按钮单击上添加这样的控件:-

protected void lnkadd_Click(object sender, EventArgs e)
{
    HtmlTableCell tCell = new HtmlTableCell();
    UserControl uc = (UserControl)Page.LoadControl("~/Controls/DirectionalPricingCtrl.ascx");
    tCell.Controls.Add(uc);
    tablerow.Cells.Add(tCell);
}
Run Code Online (Sandbox Code Playgroud)

我认为我做错了什么,我应该在页面生命周期方面添加用户控件,但是如何添加? 有人可以指导我或提供一些有用的链接吗? 当我每次单击“添加”按钮时都必须添加用户控件,然后检索所有值并将其保存到数据库时,我应该遵循什么方法?

Jar*_*cek 5

我更喜欢 javascript / ajax 解决方案,但我认为您的代码没有任何问题。

我做了一个小例子。这是与您相同的解决方案。优点是仅在单击时才加载控件。

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLink_Click(object sender, EventArgs e)
        {
            var uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
            pnl.Controls.Add(uc);            
        }
    }
Run Code Online (Sandbox Code Playgroud)

下面是在 Page_Load 事件中加载用户控件的示例,并且在单击 (btnLink_Click) 的情况下将用户控件添加到面板。它的工作原理与您的解决方案相同,但即使不需要,也可以加载用户控件(在内存中处理而不重新渲染)。

public partial class Default : System.Web.UI.Page
    {
        UserControl uc; 
        protected void Page_Load(object sender, EventArgs e)
        {
           if(IsPostBack) // This condition is not needed but we know that click is always postback
            uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
        }

        protected void btnLink_Click(object sender, EventArgs e)
        {

            pnl.Controls.Add(uc);            
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我更喜欢的解决方案,它基于可见属性。如果用户控件不可见,则不会将其呈现为输出。当然,如果表格中有很多单元格作为控制容器而不是面板,那么它不是很实用。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%@ Register Src="~/WebUserControl1.ascx" TagName="ucrCtrl" TagPrefix="ctr"  %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="btnLink" runat="server" Text="Add" OnClick="btnLink_Click" />
        <asp:Panel runat="server" ID="pnl">
            <ctr:ucrCtrl runat="server" ID="usrCtrl" Visible="false" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLink_Click(object sender, EventArgs e)
        {
            usrCtrl.Visible = true;     
        }
    }
}
Run Code Online (Sandbox Code Playgroud)