tisdag 19 juli 2011
ASP.NET Life Cycle
onsdag 6 juli 2011
ASP.NET (4): A few gotchas for dynamic controls
Do This!
To summarize: Always assign your own IDs to the controls you wish to handle postback data and events for. Make sure your IDs are valid (keep away from the colon) and make sure you re-add your controls before the LoadComplete-stage.Discussion
First and foremost, when you are using dynamic controls, make sure you create and (re)add them at the proper stages.When adding them for the first time you can do it in any stage that is before the Render-stage, such as in an Button_Click event or whatever.
You could of course override the Render-function and add controls before you call the baseclass Render-function. But then again, why would you ever want to do that?
When re-adding them, as you must do with dynamic controls if you want them to stay on the page for subsequent requests, you must do it before the LoadComplete-stage. Or else they wont be able to get their postback data and raise any events.
A suiting place to re-add them would be in the PreInit-stage or in the Init-stage. When dealing with master pages one must take extra care though, since the master page is added as a child control to the page to display, all controls on it, and any of your own controls that resides within a <asp:Content>-tag will not be available in the PreInit-stage, so then you will have to use the Init-stage, or some other stage later than that.
- A list and description of all (well, most) stages can be found at MSDN
- Concerning master pages and the order of stages (events), see MSDN for that too.
No fake IDs!
When you are not specifying your own IDs for controls, they will get one automatically assigned to them. These IDs are generated from the nearest NamingContainer and from the number of controls currently in it. This is only in the standard case though, there are configurable exceptions in ASP.NET 4.0.This means that if you do not assign your own IDs to your controls, you might face some problems with events not firing and postback data not being used. If the controls are added in exactly the same order on every request, then you might be fine. But if some of the controls are added in a different order every time, or if another control is added or removed to the NamingContainer, your automagically generated IDs will not be consistent across requests.