Visual Studio Spoiled Me, and Web Parts Framework Made Me Learn


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

http://www.sharepointblogs.com/chadclarkesmossblog/archive/2007/10/10/custom-web-part-building-state-management-tips-and-tricks.aspx

 

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.
Theme: Esquire by Matthew Buchanan.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: