SharePoint 2010 Web part Life Cycle

Following Life cycles are available in SharePoint 2010.
There are four predefined routines that take place in a WebPart Life Cycle,
  1. OnInit
  2. CreateChildControls
  3. OnPrerender
  4. Render 
OnInit: This method handles initialization of the control.
 
Example
  1. protected override void OnInit(EventArgs e)  
  2. {  
  3.    try  
  4.    {  
  5.       _divPanel = new Panel();  
  6.       _ddlCountry = new DropDownList();  
  7.   
  8.       _ddlTown = new DropDownList();  
  9.    }
  10. }
OnLoad: This event handles the Load event and also used for initialize the control. But it is not intended for loading data or other processing functionality.
 
CreateChildControls: This creates any child controls.
 
In most cases, we have to initialize the control's default value (as Text, Checked, Items, and so on) and activity that is possible to call just at first WebPart load, checking PostBack:
 
Example
  1. protected override void CreateChildControls()  
  2. {  
  3.    try  
  4.    {  
  5.       base.CreateChildControls();  
  6.       _divPanel.ID = "_divPanel";  
  7.       _divPanel.BorderStyle = BorderStyle.Ridge;  
  8.       _divPanel.Width = 250;  
  9.       _divPanel.Height = 300;  
  10.       _divPanel.BackColor = System.Drawing.Color.Gainsboro;  
  11.       Controls.Add(_divPanel);  
  12.    }
  13. }
EnsureChildControls: This method ensures that CreateChildControls has executed. EnsureChildControls method must be called to prevent null reference exceptions.
 
SaveViewState: View state of the web part saved.
 
OnPreRender: This method handles or initiates tasks such as data loading that must complete before the control can render.This is the routine where the control's value kept by ViewState (for example Item value set up by the user to DropDownList nation), is available.
 
For this reason, it's normal to begin business procedure from here, and in our case we're going to load values for the second dropdown list (Town DropDownList) with the proper data.
 
Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.
 
Render: This method is used to render everything.That's the routine for HTML rendering WebPart.
 
RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.
 
OnUnload: Performs the final clean up.
 
Thanks for learning My blogs!!! 
Ebook Download
View all
Learn
View all