简体   繁体   English

动态创建/加载用户控件只能工作一次!

[英]Dynamically creating/loading a user control only works once!

protected void addMoreDay_btn_Click(object sender, EventArgs e)
        {
            Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");
            Days_div.Controls.Add(OneMoreDay);
        }

I load my userControl dynamically to a div element.. but the problem is that it works only once.我将我的 userControl 动态加载到一个 div 元素。但问题是它只能工作一次。 .. I mean I click the addMoreDay_btn button and it works then I try to click it again it won't create another instance of my control! .. 我的意思是我单击addMoreDay_btn按钮,然后我尝试再次单击它,它不会创建我的控件的另一个实例!

Edit编辑

I think it works but it doesn't save the last created one.. it just replaces it with the newly created control.. and still I don't how to solve this!我认为它可以工作,但它不会保存最后创建的..它只是用新创建的控件替换它..我仍然不知道如何解决这个问题! =S =S

The problem is occurring because the dynamically added control is being destroyed on each postback right before it is created again.之所以会出现问题,是因为动态添加的控件在每次回发时都在再次创建之前被销毁。 In order to have dynamic controls persist across postbacks, you'll have to add them every time the page posts back.为了使动态控件在回发中持续存在,您必须在每次页面回发时添加它们。

Try the following code.试试下面的代码。 Notice that the controls are being added in the Page_Init method:请注意,控件被添加到 Page_Init 方法中:

protected void addMoreDay_btn_Click(object sender, EventArgs e)
{
    Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");
    Days_div.Controls.Add(OneMoreDay);
    Session["MyControl"] += 1
}


protected void Page_Init(object sender, EventArgs e)
{
    for (int i = 1; i <= (int)Session["MyControl"]; i++) {
        Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");
        Days_div.Controls.Add(OneMoreDay);        
    }
}

See here这里

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

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