For several days, I have struggled with a problem with the view state on dynamically loaded controls. I am using a fair number of dynamic controls on a little project that I have been working. Everything was working fine except in one section. In this one section, view state was not being tracked until after the first post back. Events were not responding until after the first post back. Everything seemed to be setup properly and it was working everywhere else.
Very perplexing. Who ever heard of a problem fixing itself like that? I have heard of dynamic controls NOT working after the second post back. This was really strange. Here I had obviously made some mistake in wiring up the dynamic controls that fixes itself after one post back.
I tried every thing I could think of to track this down. I overrode the LoadViewState method, PreRender, SaveViewState, UnLoad, etc. Everything looked good. Everything was behaving as expected after the initial post back. As hard as I looked, I couldn't see anything different between the sections that worked and the area that was misbehaving. A fresh set of eyes was needed.
Sometimes you can be too close to a situation to see what is in front of you.
I knew that it was important that the dynamic controls get the same ID when they are reloaded as they had when initially added. I took great pains to reload each control in the same order. I took great pains to unload controls that were no longer needed before adding any additional controls. What I failed to notice and only a fresh set of eyes could see was that in one place, coincidently the place having problems, I incremented the control count, added the control to the containing control's control array, and finally set its ID, using the control count. Everywhere else, I incremented the control count as the last step.
This means that for the problematic section, there would be no control 0 when the controls are originally loaded. Because I was incrementing the control count before using it, the first control would always have an ID of 1. On post back when I reloaded the dynamic controls, the control would load but be given an ID of 0 because I was using the control count and then setting it. There was no viewstate for Control 0 and there was no longer a control for the viewstate data associated with the control with ID of 1. After the first post back, the gap in the control ids was removed and from then on everything worked properly.
I hope that my struggles help someone else.