Sunday 2 March 2014

SharePoint WebPart Life Cycle

SharePoint WebPart Life Cycle
OnInit
In this event the configuration values can be set using a property bag and those that are in the web part task pane are loaded into the web part.
protected override void OnInit(EventArgs e)
{
}
LoadViewState
The view state of the web part is populated here.
protected override void LoadViewState(object savedState) //Only at Postback
{
}
OnLoad
This event is for loading the WebPart such as adding controls.
protected override void OnLoad(EventArgs e)
{
}
CreateChildControls
In this routine control properties and methods previously declared are defined. In most cases, we have to initialize the control's default value (such as Text, Checked, Items, and so on) and activity that is possible to call just at first WebPart load, checking PostBack. The controls specified are created and added to the controls collection. When the page is being rendered for the first time the method generally occurs after the OnLoad() event. In the case of postback, it is called before the OnLoad() event. We can make use of EnsureChildControls() - It checks to see if the CreateChildControls method has yet been called, and if it has not, calls it.
protected override void CreateChildControls()
{
}
OnPreRender
Here we can change any of the web part properties before the control output is drawn. This is the routine where the control's value is kept for the View State.
protected override void OnPreRender(EventArgs e)
{
}
Render
HTML Output is generated.
protected override void Render(HtmlTextWriter writer)
{
}
OnUnload
This is executed when the web part is unloaded.
protected override void OnUnload(EventArgs e)
{
}
Dispose
This to free the memory.
public override void Dispose()
{
}
---------------------
http://blogs.msdn.com/b/guruketepalli/archive/2011/11/29/visual-web-part-life-cycle.aspx
------------------
OnInit: This method handles initialization of the control.
OnLoad: This event handles the Load event. This is also used for initialize the control but is not intended for loading data or other processing functionality.
CreateChildControls: This is the most popular event in web part life cycle. This creates any child controls. So if you are adding any control to display then you have to write in this method.
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.
Page.PreRenderComplete: The page fires the PreRenderComplete event after all controls have completed their OnPreRender methods.
Render: This method is used to render everything.
RenderContents: Renders the contents of the control only, inside of the outer tags and style properties.
OnUnload: Performs the final cleanup.