Monday, May 2, 2011

How to solve "Failed to load viewstate" occasional problem for dynamically loading usercontrols in ASP.NET WebForms?


Full error message:
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 to replicate:
-Add a control dynamically to a placeholder and the control viewstate is enabled, and on the postback, add a different control to the placeholder.

Solution:
Add user control to a Panel, and Add Panel into placeholder
                placeholder.Controls.Clear();
                Panel p = new Panel();
                Control ctl = this.LoadControl(controlPath);
                ctl.ID = "uc" + i.ToString();
                i += 1;
                p.Controls.Add(ctl);
             placeholder.Controls.Add(p);


Reference:

http://forums.asp.net/p/1295517/2526944.aspx

No comments:

Post a Comment