Adding a control a runtime : what is not in the viewstate

In several earlier post on adding controls at runtime and the potential impact on the viewstate I could have created some confusion. You can add controls at runtime but these controls will not become part of the viewstate of their parent control (the page itself is also a control). If you want to persist the new control over  roundtrips you have to add the control again and again on every roundtrip. The viewstate is used to store all those properties which pop up in the property window.


Instead of adding a control again and again I personally prefer to add the control at design time and set its visible property to false. When the control is needed it will become available by setting the property programmtically. An even nicer way is to bind the visible property to a custom expression, like the name of a (protected) method on the page.


Peter

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://codebetter.com/blogs/peter.van.ooijen/ pvanooijen

    The link is updated and works again. Just follow that for a code example.

  • noob

    and how do you do that?

  • Peter van Ooijen

    Responses on earlier posts indicate that some people expect the control to be re-created because it is in the viewstate. That’s the myth I wanted to get out of the way.

    There’s a good chance it will participate in the viewstate if you recreate it before the page starts tracking viewstate. That’s in the init. I agree on that.

  • Paul Wilson

    Two things:

    (1) The dynamically created control does fully participate in viewstate — it just isn’t automatically recreated, nor should it be since you may not want that behavior at all. But if you choose to recreate it, all of its properties that usually save into viewstate will in fact be restored from viewstate — although you should create it as early as possible for everything to sync up, and you have to recreate it in the same spot in the control tree.

    (2) Denis Bauer (http://www.DenisBauer.com) has a free custom placeholder control that will automatically recreate all dynamic controls that you add to it, so check it out.