简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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