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

我將我的 userControl 動態加載到一個 div 元素。但問題是它只能工作一次。 .. 我的意思是我單擊addMoreDay_btn按鈕,然后我嘗試再次單擊它,它不會創建我的控件的另一個實例!

編輯

我認為它可以工作,但它不會保存最后創建的..它只是用新創建的控件替換它..我仍然不知道如何解決這個問題! =S

之所以會出現問題,是因為動態添加的控件在每次回發時都在再次創建之前被銷毀。 為了使動態控件在回發中持續存在,您必須在每次頁面回發時添加它們。

試試下面的代碼。 請注意,控件被添加到 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);        
    }
}

這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM