Friday, February 11, 2011

How do I properly handle the viewstate of a child control within a composite control?

I have a composite control that contains a ListBox child control. On postback, the items for the ListBox disappear. I have a property for the ListBox that initializes it, and I add it to the controls collection in CreateChildControls. Am I doing something wrong? Do I need to be doing something else to properly handle the viewstate of this ListBox?

  • Be sure to add your control to the parent before you add listitems or databind. Otherwise, your composite control won't track viewstate on your ListBox's listitems.

    Here's a more thorough explanation: http://scottonwriting.net/sowblog/posts/2129.aspx.

    Jeremy Cantrell : i'm not databinding. i just add some items to the listbox during the initial page load.
    Corbin March : Do add the items before or after you add the ListBox to the parent? Make sure it's after. If you're doing it onload, be sure to call EnsureChildControls() before you add the items. That guarantees CreateChildControls() has run.
    Jeremy Cantrell : if i'm adding the items in the page that contains the composite control, how can i be sure that createchildcontrols has already happened?
    Corbin March : Maybe set them via a public function and call EnsureChildControls() inside.
    Jeremy Cantrell : There was no databinding going on, but this was basically the problem. I'm marking as answered.

0 comments:

Post a Comment