简体   繁体   English

ASP.NET用户控件 - 以编程方式添加多个实例的问题?

[英]ASP.NET User Controls - Problem adding multiple instances programmatically?

I have created a user control which basically consists of 3 text boxes. 我创建了一个用户控件,它基本上由3个文本框组成。 I want to allow the user to click a hyperlink which will add a new instance of the user control onto a PlaceHolder. 我想允许用户单击一个超链接,该超链接将在PlaceHolder上添加用户控件的新实例。 This seems to be working as I populate one of the text box controls with a random number which changes whenever I click the hyperlink. 这似乎是有效的,因为我用一个随机数填充其中一个文本框控件,每当我点击超链接时它都会改变。 However, it is overwriting the previous control. 但是,它覆盖了以前的控件。

Heres the code on MyPage.aspx 继承人MyPage.aspx上的代码

protected void MyHyperlink_Click(object sender, EventArgs e)
{
     var uc = new MyUserControl();
     uc = (MyUserControl)LoadControl("~/path/to/my/usercontrol.ascx");
     placeHolderCtrl.Controls.Add(uc);
}

Basically what I need to know is how can I get the control adding different instances underneath eachother as it just seems to be 1 control being overwritten each time. 基本上我需要知道的是如何让控件在彼此之下添加不同的实例,因为它似乎每次都被覆盖1个控件。

Thanks. 谢谢。

The problem is after the postback, your previously added controls are not added to the placeholder. 问题是在回发之后,您之前添加的控件未添加到占位符。 Dynamically added control should be added on each postback. 应在每次回发时添加动态添加的控件。 My recommendation is to store a counter in a variable and at your page load, add your web controls again depending to this counter. 我的建议是将计数器存储在变量和页面加载中,根据此计数器再次添加Web控件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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