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

发布于 2024-11-24 05:54:49 字数 455 浏览 0 评论 0原文

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

我将 userControl 动态加载到 div 元素..但问题是它只能工作一次! .. 我的意思是我单击 addMoreDay_btn 按钮,它起作用了,然后我尝试再次单击它,它不会创建我的控件的另一个实例!

编辑

我认为它可以工作,但它不会保存最后创建的控件..它只是用新创建的控件替换它..但我仍然不知道如何解决这个问题! =S

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! .. 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!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

め七分饶幸 2024-12-01 05:54:49

出现此问题的原因是动态添加的控件在每次回发时在再次创建之前被销毁。为了让动态控件在回发过程中持续存在,您必须在每次页面回发时添加它们。

尝试以下代码。请注意,控件是在 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);        
    }
}

请参阅 此处

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:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文