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

我的页面上有一个用户控件( UserControl1 )和一个Add more按钮。单击Add More按钮再次添加相同的用户控件。当我第一次点击用户控件时,它会添加第二个User Control,但是第二次它没有添加其他。我认为控件丢失了。 我在链接按钮点击上添加这样的控件: –

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

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

我更喜欢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); } } 

以下是在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); } } 

这是我更喜欢的解决方案,它基于可见属性。 如果用户控件不可见,则不会将其呈现为输出。 当然,如果桌子上有很多细胞作为对照容器而不是面板,那么它不是很实用。

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <%@ Register Src="~/WebUserControl1.ascx" TagName="ucrCtrl" TagPrefix="ctr" %>       
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; } } }

您以编程方式添加控件的代码是正确的。 试试做,

 tablerow.Cells.Add(tCell); 

而不是将其添加到控件。 这看起来像一个控件渲染问题。

你认为没错,你的控件会丢失,因为缺少一个应该处理回发的程序。 无论何时定义控件类的变量(如HtmlTableCell),都应该自己处理从发布页面保存和加载数据所需的所有过程,而不是使用asp.net运行时引擎提供的预定义过程。

最好在Postback期间在一些存储位置保存和加载这些控件,例如在PageLoad上的每个post-back上的ViewState,然后,在lnkadd_Click方法中处理添加/删除额外控件。