When a Web server control is created dynamically at run time, some information about the control is stored in the view state that is rendered with the page. When the page is posted back to the server, however, non-dynamic controls (those defined on the page) are instantiated in the page's
In most scenarios, this view state processing model works fine. Typically, you add dynamic controls to the end of a container's collection of controls. The view state information stored for the dynamic controls is therefore extra information at the end of the view state structure for the appropriate container, and the page can ignore it until after the controls are created.
However, view state information about dynamically created controls can be a problem in two scenarios:
-
If you insert dynamic controls between existing controls.
-
If you insert controls dynamically and then reinsert them during a round trip, but with different values.
If you insert dynamic controls between existing controls, the dynamic control's view state information is inserted into the corresponding location of the view state structure. When the page is posted and the view state is loaded, the dynamic control does not yet exist; therefore, the extra information in view state does not correspond to the right control. The result is usually an error indicating an invalid cast.
If you reinsert controls with each round trip, each generation of dynamically created controls will pick up property values from the view state of the preceding set of controls. In many cases, you can avoid this problem by setting the
For details about view state, see
ASP.NET Page Life Cycle Overview
ASP.NET State Management Overview, and