Condividi tramite


Dynamic Web Server Controls and View State

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 Init event and view state information is loaded before the dynamic controls can be recreated (generally in the Page_Load handler). Effectively, before the dynamic controls are recreated, view state is temporarily out of sync with the page's controls. After the Page_Load event has run, but before control event-handling methods are called, the remaining view state information is loaded into the dynamically created controls.

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 EnableViewState property of the container control to false. In that case, no information about the dynamic controls is saved, and there is no conflict with successive versions of the controls.

For details about view state, see

ASP.NET Page Life Cycle Overview

ASP.NET State Management Overview, and ViewState.

See Also

Other Resources

Adding ASP.NET Controls Programmatically

Setting ASP.NET Server Control Properties Programmatically