Suppose I have a treeview, where each treenode contains an id for a different set of user controls. When the user clicks a node, these controls should be loaded to the page. As I understand the ASP page life cycle, dynamic controls should be added in the initialization stage, and postback events will fire later on.
So if the treeview click event happens after I need to add my controls, how do I dynamically add controls based on user postback events?
Edit: I tried the suggestion from ArronLS:
What I did was add the node value to the session array, and use that when I do the init to choose which form elements to load to the controls of a placeholder control. On the treeview click event, I update the node in the session array, clear the old form elements in the placeholder, and add the new form elements to the controls. When the page is loaded again, it should now find the node at init time, so viewstate problems would be circumvented.
Now I haven’t fully tested this yet, but there was another similar post that talks about the problems that might result with the viewstate. They suggest a solution that polls the Request[] part of the context (in their case the dropbox) within the Init control, manually handling some of the postback functionality.
My new question is how to I access the selected node in the treeview using the Request array?
The consequence of not loading the controls in init is that if there are changes to properties in the view state, these will not get persisted to the controls. For example, if on the first request of the page, you dynamically create controls in init, then on the post back you create them again in init, then after init, any property values in viewstate get applied to the control.
So if you created the control initially in a treeview click event, I would guess that should be fine, because there is not yet any viewstate accumulated to apply to the control since it was just created. However, I am not sure if this will cause the control to not save viewstate. You’d have to experiment with that.
On subsequent postbacks after the first, now you will need to create the control in init for accumulated viestate to be applied to it, so you’ll need some mechanism to “remember” that you created the control once before, initially in response to the click event, and then on subsequent postbacks create the control again in init. You have to recreate the control on each request, if you didn’t know that.
So the question becomes how important is the viewstate for the control.
Edit: I will also add that I am not entirely sure if there would be other consequence other than how this affects viewstate.