Through much trial and error and research on the web, I have come up with the guidelines for dealing with dynamically loaded controls.
- Load the controls in the same order on each post back
- Add new controls to the Controls array before setting any properties. Properties set before the control is added to the control array will not be tracked in View State.
- If an event handled after dynamic controls are added causes diferent controls to be loaded, the newly reloaded controls may need to be explicitely unloaded.
- For example, if a page has dynamic controls added based on the month selected, when the user selects a different month, the existing controls will need to be unloaded before the new controls are added.
- When removing the dynamic controls, start at the end of the list and work your way backward.
- Rewire any event handlers as soon as the control is reloaded on each post back.
I found the following articles very helpful:
http://clariusconsulting.net/blogs/vga/archive/2003/08/11/66.aspx Dispells the myths about when to reload dynamic controls
http://scottonwriting.net/sowblog/posts/2129.aspx Clears up some misconceptions that I had about viewstate. Points out the importance of adding the control to the controls array before setting any properties.