简体   繁体   中英

Dymanically added user controls disapper on postback in asp.net

I have a asp.net listbox which is populated in Page_Load event if it is not postback. Whenever users selects any item from the asp.net listbox, I need to load usercontrols based upon how many items were selected from the listbox. I have been able to load multiple controls; however, my problem is those newly added controls get disapper on postback.

Here is my sample code

 if (!this.IsPostback)
    {
bindListBox();

    }

private void bindListBox()
{
lstAgenyList .DataSource = GetAgenyList();
lstAgenyList.DataTextField = "Id";
lstAgenyList.DataValueField = "Name";
lstAgenyList.DataBind();
}

protected void lstAgenyList_OnSelectedIndexChanged(object sender, EventArgs e)
{

foreach(Item in lstAgenyList.items) {
if(item.Selected)
{
addControls(item.Text, item.Value);
}
}

}

private void addControls(string itemName, string itemValue)
{
var control = this.LoadControl("~/Controls/a.ascx");
control.id= itemName.Trim() + itemValue + "Controls_";
this.agenyListPlaceHolder.Controls.add(control);

}

So my questons to you guys, what are the best options for implementing logic like this in asp.net web form.

It has to do with PlaceHolder and dynamically added controls.

Answer to almost the same question is here: http://forums.asp.net/t/1623719.aspx

Basically, everyting in placeholder will be lost upon post back and you have to re-add it back into it during PreInit event from hidden fields, Request.Form, or ViewState.

控件消失是因为维护动态添加的控件的状态是我们的责任,您想尝试一下占位

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