It took me sometime until I figured out some facts about Web Parts lifecycle. The following are some findings I believe will make you rethink what methods and events to override to develop a Web Part:
- CreateChildControls() is – from what it is – used to create controls for layout and content. It’s not meant to create the content itself or have manipulation logic.
- Make sure you do all the stitching of Event Handlers to their respective controls in this method.
- CreateChildControls() is called all the time! whether on initializing or post back, it gets called. So make sure you don’t override anything while coding this method:
- ViewState[] and Session[] can be used to track view state or persistent session information in the Web Part life cycle.
- ViewState[] and Session[] should not be initialized in this method. Use the constructor or OnInit() event for this purpose.
- Your logic should go into events for those controls you’re creating in CreateChildControls()
- Ensure fetching data for your controls doesn’t happen each time CreateChildControls() gets called.
- It’s better to utilize OnPreRender() event for this purpose, and protect the data fetch block with a condition to avoid executing on post backs.
- IsPostBack is not a trusted condition for the behavior in Web Parts, and this is because a post back can be triggered while in design mode, where the user has just added the web part!
Few posts that could be helpful:
http://www.codeproject.com/KB/sharepoint/WebPartLifeCycle.aspx
http://www.sharepoint-tips.com/2007/03/server-side-controls-and-data-binding.html