简体   繁体   中英

Dynamic Add User Control and ViewState

I want to add user control to my page dynamically. I wrote this code that every time that DropDownList changed, appropriate user control should rendered:

if (!IsPostBack)
{
    BindMainReports();
}
else
{
    PlaceHolderControls.Controls.Clear();
    if (drpReportType.SelectedValue != "-" && drpReportType.SelectedValue != "")
    {
        Control ctrl = Page.LoadControl("UC/Reports/" + drpReportType.SelectedValue + ".ascx");
        PlaceHolderControls.Controls.Add(ctrl);
    }
}

this code works fine for first time but when I change DropDownList for second time I get this error:

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

How I can solve the problem.

thanks

只需为PlaceHolderControls添加EnableViewState="false"

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