views:

469

answers:

1

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?

+1  A: 

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.

Corbin March
i'm not databinding. i just add some items to the listbox during the initial page load.
Jeremy Cantrell
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.
Corbin March
if i'm adding the items in the page that contains the composite control, how can i be sure that createchildcontrols has already happened?
Jeremy Cantrell
Maybe set them via a public function and call EnsureChildControls() inside.
Corbin March
There was no databinding going on, but this was basically the problem. I'm marking as answered.
Jeremy Cantrell