Rob Garrett - Blogs

Welcome to Rob Garrett - Blogs Sign in | Join | Help
in Search
Google

Software/Technology Discussion

Software and Technology Tid-bits

ViewState Tracking in ASP.NET Controls

Let's say you have the following snippet of code below. The code dynamically instantiates a new ASP.NET control, changes the title property and then adds the control to the control collection of a placeholder on the page - a typical approach to dynamically creating controls.  When the control loads, it adds an item into the drop down list items collection with the same name as the current title property value.  The title property of the control stores it's value in the ViewState, so that the title value is retained between page post backs.  The problem is, this code does not work as expected. After a post back the value of the title property is lost - why?


Finding the answer to this problem took some digging buy a co-worker - The problem occurs because the control is not tracked by the ViewState until the control is added to the parent container's control collection. Once the control is added to the control collection of the placeholder, ViewState tracking is turned on and changes to the title property are then stored in the ViewState.  In the above example, the title of the control was assigned before the control was added to the placeholder control collection, so the ViewState had not tracked a change to the title, and therefore did not persist the value.

When dynamically creating user or server controls in ASP.NET always add the control to the container controls collection before manipulating the ViewState.

The code below fixes the problem:
Share this post: Email it! | bookmark it! | digg it! | reddit!
Published Wednesday, July 13, 2005 11:50 AM by Rob Garrett

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

Blurb


Head Shot
Rob Garrett is a British Expat living in Maryland USA. Rob is a trained software engineer and experienced in Windows .NET development.

Rob enjoys listening to Rock music, posting to blogs, driving in the country with the sunroof open, beer (not in conjunction with country driving) and spending time with his family.

This Blog

Syndication

Powered by Community Server, by Telligent Systems