动态添加用户控件和ViewState

Dynamic Add User Control and ViewState

我想将用户控件动态添加到我的页面。我编写了这段代码,每次 DropDownList 更改时,都应呈现适当的用户控件:

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

此代码第一次运行良好,但当我第二次更改 DropDownList 时出现此错误:

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.

我该如何解决这个问题。

谢谢

只需为 PlaceHolderControls

添加 EnableViewState="false"