Click here to Skip to main content
Click here to Skip to main content

WebPart Life Cycle

, 1 Dec 2007
Rate this:
Please Sign up or sign in to vote.
This article examines the production of a simple WebPart in C#

Introduction

In Sharepoint 2007, a way to customize the environment pass is by building WebParts coded with one of the languages available in VS2005. In this article, we're going to examine the production of a simple WebPart in C#, to better comprehend the life cycle and later, look at events that the developer has to consider in order to get the correct execution of code.

Use Case Description

In this sample will be proposed a typical case where the selection of an item in a dropdown list raises the event of filling a second dropdown list (server-side event) with proper items to the value selected. Specifically, the first dropdown list contains a short nations list, the second dropdown list will be loaded with a short town list belonging to the nation selected.

Besides the two dropdown lists are shown the steps regarding principal event routines and property Text of DropDownList nation.

The complete Webpart will have the following rendering graphic:

Screenshot - image001.jpg

The Web Part

It is interesting to note that DropDownList nation has set ViewState and AutoPostBack to true. The article scope is to highlight the WebPart life Cycle and understand when the value of a control (i.e. Text property) that has ViewState set up to be true, becomes available. In practice, this happens when the user selects a nation changing the first dropdown list item which starts the Postback event, at which point the value of the new item is available.

The Code

As is possible to understand by the shown log, there are four predefined routines that take place in a WebPart Life Cycle:

  1. OnInit: Typically in this routine we define controls that will be involved with WebPart:
    protected override void OnInit(EventArgs e)
    {
        try
        {
            _divPanel = new Panel();
            _ddlCountry = new DropDownList();
    
            _ddlTown = new DropDownList(); 
  2. CreateChildControls: In this routine are defined control properties and methods previously declared. 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:
    protected override void CreateChildControls()
    {
        try
        {
            base.CreateChildControls();
            _divPanel.ID = "_divPanel";
            _divPanel.BorderStyle = BorderStyle.Ridge;
            _divPanel.Width = 250;
            _divPanel.Height = 300;
            _divPanel.BackColor = System.Drawing.Color.Gainsboro;
            Controls.Add(_divPanel);
            _ddlCountry.AutoPostBack = true;
            _ddlCountry.ID = "_ddlCountry";
            _ddlCountry.Width = 150;
            _ddlCountry.EnableViewState = true;
            _ddlCountry.SelectedIndexChanged +=
                new EventHandler(_ddlCountry_SelectedIndexChanged);
            _divPanel.Controls.Add(_ddlCountry);
            _ddlTown.AutoPostBack = false;
            _ddlTown.ID = "_ddlTown";
            _ddlTown.Width = 150;
            _ddlTown.EnableViewState = true;
            _divPanel.Controls.Add(_ddlTown);
    
            if (!Page.IsPostBack)
                ddlCountry_Load();
  3. OnPreRender: 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:
    protected override void OnPreRender(EventArgs e)
    {
        try
        {
            _sMex += "OnPreRender: " + _ddlCountry.Text + " ";
            string sStateSelected = _ddlCountry.Text;
            _ddlTown.Items.Clear();
    
            switch (sStateSelected)
            {
                case "England":
                ddlTown_Load("London", "Liverpool", "Bristol");
                break;
    
                case "Spain":
                ddlTown_Load("Madrid", "Barcelona", "Valencia");
                break;
    
                case "Italy":
                ddlTown_Load("Rome", "Milan", "Florence");
                break;
    
                default:
                ddlTown_Load("New York", "Tokio", "Paris");
                break;
            }
  4. Render: That's the routine for HTML rendering WebPart:
    protected override void Render(HtmlTextWriter writer)
    {
        _sMex += "Render: " + _ddlCountry.Text + " <br />";
        writer.Write("        <div id='_divPanel'>");
        writer.Write("            <table style='border-right: 1px ridge; 
                border-top: 1px ridge; border-left: 1px ridge;");
        writer.Write("                border-bottom: 1px ridge; 
                background-color: gainsboro;' 
                cellpadding='3' cellspacing='2'");
        writer.Write("                width='250'>");
    
        if (_sErrDescription == "")
        {
            // dropdownlist State
            writer.Write("                <tr style='border-right: 
                1px ridge; border-top: 1px ridge; border-left: 1px ridge;");
            writer.Write("                    border-bottom: 1px ridge;'>");
            writer.Write("                    <td style='height: 50px'>");
            _ddlCountry.RenderControl(writer);
            writer.Write("                    </td>");
            writer.Write("                </tr>");
    
            // dropdownlist town
            writer.Write("                <tr style='border-right: 1px ridge;
                border-top: 1px ridge; border-left: 1px ridge;");
            writer.Write("                    border-bottom: 1px ridge;'>");
            writer.Write("                    <td style='height: 50px'>");
            _ddlTown.RenderControl(writer);
            writer.Write("                    </td>");
            writer.Write("                </tr>");
        }

In Depth Examination

The goal of this article is to clarify a WebPart life cycle in the essential steps and to focus the use of ViewState for business logic. To build advanced WebParts of course, it is necessary to go deeper into this and other concepts and naturally write more code lines.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Fabio Barbieri

Ireland Ireland
I am Microsoft analyst and developer

Comments and Discussions

 
QuestionWhy can't we use Nation Drop down list's Selection changed Event? Pinmembervenkat vangal17-May-12 1:29 
GeneralMy vote of 3 PinmemberNarulaSrinivas28-Jun-11 21:39 
GeneralWebpart Life cycle PinmemberSeathestar1-Feb-11 23:19 
GeneralMy vote of 1 Pinmemberchris17517-Jan-11 2:49 
GeneralMy vote of 1 Pinmemberbalakrishna.ch27-Sep-10 21:11 
QuestionWhy panel Control created in CreateChildControlMethod and not rendred in render method? Pinmemberravi.khambhati8-May-10 22:50 
AnswerRe: Why panel Control created in CreateChildControlMethod and not rendred in render method? Pinmemberewtwe678976917-Apr-13 4:04 
GeneralMy vote of 1 Pinmemberrhino1799-Mar-09 7:46 
GeneralI gave it 4 Pinmemberjavaman591-Jun-10 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 1 Dec 2007
Article Copyright 2007 by Fabio Barbieri
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid