Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Introduction to Web Parts

0.00/5 (No votes)
1 Mar 2007 1  
A brief introoduction to using WebParts in your applications

Introduction

It would not be wrong to say that web parts are going to be the future of web based management systems. Web parts give us option of drag and drop of objects on a page, change titles, border style, properties of objects on runtime. Before the introduction of web parts it was used to be a hectic task because we had to write a lot of java script and to save the state of contents in a database.

There are two basic things in web parts:

  • Web part manager.
  • Web part zones.

Web Part Manager

Web part manager is a manager for web parts behind the scene. We normally don't do a lot of things with the web part manager either in code or in design mode.

Web Part Zones

There are four kind of zones in web parts

  • Web Part Zone
  • Editor Zone
  • Catalog Zone
  • Connection Zone

Web Part Zone

It's a basic unit of web parts. By placing different contents in a web part zone we can allow a user to drag and drop contents on a page.

To use different zones place a dropdown list and add following items in it.

  1. Browse
  2. Display
  3. Edit
  4. Catalog
  5. Connect

Write down following code on onChangeIndex event of this dropdown list.

if (cmbOptions.SelectedValue == "Design")
{
    WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
else if (cmbOptions.SelectedValue == "Browse")
{
    WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (cmbOptions.SelectedValue == "Catalog")
{
    WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}
else if (cmbOptions.SelectedValue == "Edit")
{
    WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
}
else if (cmbOptions.SelectedValue == "Connect")
{
    WebPartManager1.DisplayMode = WebPartManager.ConnectDisplayMode;
}

1: Browse mode

Browse mode is default mode of webparts. In browse mode we cannot drag and drop the web parts but we can see two options: minimize and close. Minimizing a web part will still show it, but in minimized state. As you can see in following screenshot.

If you select close then it can be restored only in catalog mode and we will see later in this article how to use that.

2: Design mode

In design mode we can drag drop objects between web parts as you can see in following screenshot. There are two web parts named as 'links' and 'Search'.

3: Edit mode

In edit mode we can edit web parts on runtime as well. Editing of a web part is further divided into four types: Appearance, Behavior, Property, Layout. We will see first how to use Appearance and LayoutEditorPart.

AppearanceEditorPart and LayoutEditorPart

Place editor zone on the page.

Place AppearanceEditorPart, LayoutEditorPart in editor zone.

Run the application and select edit mode from option box.

Click edit from the menu available for webparts.

And you will see following output.

We can change the title of web parts here. We can see some basic options in edit mode. The Chrome type is about border and title style. Chrome state gives us option of minimizing it or not.

PropertyGridEditorPart

By using property editor we can change properties of objects in our web parts. In our example we are going to change CSSClass property of the object. To use this we will follow the same method of editor parts.

  1. Place editor zone on the page.
  2. Place a PropertyGridEditorPart inside editor zone.

To use editor zone add a new user control in project.

  1. Place a textbox on it.
  2. Place this user control in a web part of a web form.

In code behind of user control write down following code.

string _cssClass = "FrmTxtBox";
[WebBrowsable(), Personalizable(true)]
public string CssClass
{
    get { return _cssClass; }
    set
    {
        TextBox1.CssClass= value;
    }
}
protected void Page_Load(Object sender, EventArgs e)
{
    TextBox1.CssClass = CssClass;
}

As we can see in above code that we have changed a textbox's css class by using a property. And we will change this property value in a web parts edit mode.

WebBrowsable() Attribute

It allows a web part to display property in web browser in edit mode.

Personalizable() Attribute

It allows a property to be editable.

Now run this page. Suppose we choose edit mode from options combo. We will see following edit button in options menu of web part.

On selection of edit link from webpart menu we will have CssClass property in edit mode.

As we can see this textbox has FrmTxtBox named class applied on it by default. It is defined in stylesheet with attributes of border color in black.

To apply a different class named as CustomClass1, I have created this class in stylesheet and this class has no border color defined in it.

After changing the CssClass name, press the OK button. And you will see textbox with default border style.

So in this way we change properties of objects using web parts.

4: Catalog mode

Catalog mode gives us option to add/remove web parts on runtime. Say for example we have a few modules like weather, news, shopping, horoscope etc. and want to give users an option to show or hide these modules on runtime, we can accomplish this task by catalog mode.

Catalog zone is further divided into three types: Page, Declarative, Import.

Add a Catalog zone on the page. Then add PageCatalogPart, DeclarativeCatalogPart, ImportCatalogPart in catalog zone.

We can show web parts with the help of Page catalog which are closed by using 'close' option of web part, as you can see in following screenshot.

Page catalog displays the number of web parts which are closed by using this option.

Declarative catalog displays the number of elements which are added in design mode in catalog zone. Click on the smart tag option of declarative catalog zone and select edit template. Add controls in the catalog zone.

Import Catalog displays number of elements which are selected to import.

We can import files having extension '.WebPart'.

To export a file as a .WebPart type file aad following line to web.config.

<webParts enableExport="true"></webParts>

Then we can follow one of these two methods

1. Set the ExportMode property of the control to all. If your control is derived from WebPart, you can do this in markup as shown in the following example.

<aspSample:CustomWebPart id="Sample" runat="server" ExportMode="All" />

2. Or write following code on page load.

Dim gwp As GenericWebPart
gwp = WebUserControl2_1.Parent
gwp.ExportMode = WebPartExportMode.All

Now we can add any of these web parts to the page, by selecting control and the zone where we want to add it.

Connect mode

This mode allows web parts to communicate with each other. We can make static connections once (in our code) or we can allow users to connect on runtime according to their needs.

Connection mode doesn't mean to connect to database but to connect web parts together. Say for example if we have a web part having a grid, displaying some records and we want to filter it on user input. We can put a textbox for user input, in other web part and can send text by using connect mode.

In our example we will place two web parts on a page. One will be for user input and other for showing it.

Create two user controls, One will be named as provider and other as consumer. Place these two controls in web parts. Add a new class in the App_Code directory and name it ITextProvider.

Enter the following code in it.

public interface ITextToPass
{
    string GetText();
}

We are going to use this interface in both provider and consumer user controls to pass text between these two entities.

Place a textbox in Provider user control and write down following text in code behind.

public partial class ProviderWebPart : System.Web.UI.UserControl, 
                                       ITextToPass
{ 
    [ConnectionProvider("TextToPass", "TextProvider")]
    public ITextToPass GetTextTransferInterface()
    {
        return ((ITextToPass)(this));
    }

    public string GetText()
    {
        return TextBox1.Text;
    }
}

As you can see we are implementing interface which we have just created. By using this interface we return text entered in textbox to pass to consumer user control.

Using the ConnectionProvider attribute means exposing a web part exposes a connection point. For detail you can read following article.

Place a label in the consumer webpart and add write down following code in its .cs file.

public partial class ConsumerWebpart : System.Web.UI.UserControl
{
    [ConnectionConsumer("Text", "TextConsumer")]
    public void GetTextTransferInterface(ITextToPass provider)
    {
        Label1.Text = provider.GetText();
    }
}

The consumer connection point doesn't return any value. It utilizes the value from provider by using ITextToPass interface.

Now on selecting connection mode of the WebpartManager, we can see connect option in webpart's menu.

For the sake of simplicity I have changed the text of button. When we click connect we will see following screen.

Click on Create a connection to a Consumer and you will see following screen.

Select the web part as a consumer from combo.

You will see the following screen to enter text to pass to consumer.

Pass string 'A String' for the consumer

You can see in following screen that consumer webpart shows text in a label which we have passed to it.

So in this way we can pass values from one web part to another.

As I mentioned earlier we can set static connections in our code, so users will not be able to set provider and consumer by themselves.

Saving Page State In Database

Before we run the project, one question which arises in mind is that where is this page setting going to be saved for each user? Any page setting modified by users will remain as it is, these settings are saved in database. In our scenario we are going to use built in login and sign up control.

  1. Modify authentication mode to Forms in Web.Config file.
  2. Add a new file to project 'Login.aspx'.
  3. Place a login control in it, and set DestinationPageUrl to default.aspx.
  4. Add another file to project 'Signup.aspx'.
  5. Add signup control on this page, for signup.
  6. Also make sure that Sql Express services is started.

On signup using these controls a database named as 'ASPNETDB.mdf' is automatically created in the application's app_data folder. And this database has appropriate tables and stored procedure to save page state according to each user.

This is default setting and a page's setting is saved in this database according to each user logged in. This setting is mentioned in machine.config file, to customize that we need to override these settings in our application's web.config file.

Table named aspnet_users saves user basic information. aspnet_PersonalizationPerUser table saves page settings according to userid. Page setting is saved in serialized format, in PageSettings field.

Customizing the Database

By default webparts use the ASPNETDB.mdf file, so the question is how can we use our application's database for webparts.

Setting Up the Database

To customize a database for webparts run the utility named as aspnet_regsql.exe. It is present in the \Windows\Framework\v2.0.50727 subdirectory. This utility helps us to create tables and stored procedures required to customize database. Following is the screenshot of wizard provided by this utility:

This wizard creates following tables in database which we select during this wizard:

On more thing which we need to do is to customize our web.config file.

Following is the setting for web.config file:

As I mentioned earlier settings for database is mentioned in machine.config file, to customize that we need to override these settings in our application's web.config file.

Initially we define a connectionstring.

LocalSqlServer is the name of connection string in machine.config file as well, so to override this we will mention the same connection string name.

ApplicationName is any name which can mention for identification of our application, for my application I have set application name CustomConnections. It can be any.

So in this way we can customize the database for a database other then ASPNETDB.

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