简体   繁体   English

动态添加用户控件和ViewState

[英]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: 我编写了这段代码,每次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);
    }
}

this code works fine for first time but when I change DropDownList for second time I get this error: 这段代码第一次正常工作,但是当我第二次更改DropDownList时,出现此错误:

Failed to load viewstate. 无法加载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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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