Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

WebPart Life Cycle

3.00/5 (7 votes)
1 Dec 20072 min read 2   488  
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:
    C#
    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:
    C#
    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:
    C#
    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:
    C#
    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