Click here to Skip to main content
6,594,432 members and growing! (16,354 online)
Email Password   helpLost your password?
Enterprise Systems » SharePoint Server » Web Parts     Intermediate

WebPart Life Cycle

By Fabio Barbieri

This article examines the production of a simple WebPart in C#
C#, Windows, .NET, Visual Studio, Dev
Posted:1 Dec 2007
Views:20,983
Bookmarked:29 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
4 votes for this article.
Popularity: 2.05 Rating: 3.40 out of 5
2 votes, 50.0%
1

2
1 vote, 25.0%
3

4
1 vote, 25.0%
5

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

About the Author

Fabio Barbieri


Member
I am Microsoft analyst and developer
Location: Italy Italy

Other popular SharePoint Server articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 1 of 1 (Total in Forum: 1) (Refresh)FirstPrevNext
GeneralMy vote of 1 Pinmemberrhino1797:46 9 Mar '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 1 Dec 2007
Editor: Deeksha Shenoy
Copyright 2007 by Fabio Barbieri
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project