Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Article

Introduction to Web Parts

Rate me:
Please Sign up or sign in to vote.
4.33/5 (26 votes)
1 Mar 20079 min read 170.8K   131   50
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.

Image 1

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.

C#
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.

Image 2

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'.

Image 3

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.

Image 4

And you will see following output.

Image 5

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.

C#
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.

Image 6

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

Image 7

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.

Image 8

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.

Image 9

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.

Image 10

Image 11

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.

XML
<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.

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

2. Or write following code on page load.

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

Image 12

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.

C#
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.

C#
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.

C#
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.

Image 13

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

Image 14

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

Select the web part as a consumer from combo.

Image 15

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

Pass string 'A String' for the consumer

Image 16

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

Image 17

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.

Image 18

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:

Image 19

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

Image 20

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

Following is the setting for web.config file:

Image 21

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


Written By
Technical Lead
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionwebpart of weather Pin
Member 822843222-May-12 18:53
Member 822843222-May-12 18:53 
AnswerRe: webpart of weather Pin
Abdul Sami, PMP22-May-12 18:58
Abdul Sami, PMP22-May-12 18:58 
GeneralRe: webpart of weather Pin
Member 822843222-May-12 19:27
Member 822843222-May-12 19:27 
GeneralRe: webpart of weather Pin
Member 822843222-May-12 19:40
Member 822843222-May-12 19:40 
GeneralRe: webpart of weather Pin
Abdul Sami, PMP22-May-12 19:50
Abdul Sami, PMP22-May-12 19:50 
GeneralMy vote of 5 Pin
emperorxmt6-Feb-11 7:51
emperorxmt6-Feb-11 7:51 
Generalonline mobile chatting Pin
shibukannan16-Jul-09 7:32
shibukannan16-Jul-09 7:32 
GeneralMy vote of 2 Pin
santosh d21-Apr-09 19:06
santosh d21-Apr-09 19:06 
QuestionWHERE IS SOURCE CODE? Pin
santosh d21-Apr-09 19:05
santosh d21-Apr-09 19:05 
GeneralProviders in web.config Pin
jzonthemtn29-Oct-08 4:55
jzonthemtn29-Oct-08 4:55 
The Providers now go under the WebParts section of web.config:

<webParts>
   <personalization defaultProvider="asdf">
     <providers>
       <clear />
       <add connectionStringName="dbconnectionstring"
           name="asdf" type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
     </providers>
   </personalization>
 </webParts>

QuestionLinking Webparts to the Catalog web part of another page Pin
madugulad8-Aug-08 0:35
madugulad8-Aug-08 0:35 
AnswerRe: Linking Webparts to the Catalog web part of another page Pin
Abdul Sami, PMP8-Aug-08 20:50
Abdul Sami, PMP8-Aug-08 20:50 
GeneralPls send me the SourceProject Pin
speedriser20-May-08 22:43
speedriser20-May-08 22:43 
QuestionDynamic creation of webpart Pin
Rockrebel18-Apr-08 1:13
Rockrebel18-Apr-08 1:13 
GeneralRe: Dynamic creation of webpart Pin
Abdul Sami, PMP19-Apr-08 7:09
Abdul Sami, PMP19-Apr-08 7:09 
GeneralNice Article Pin
Sajudeen Kassim7-Apr-08 2:21
Sajudeen Kassim7-Apr-08 2:21 
Generalanother issue [modified] Pin
basemsayej21-Nov-07 23:01
basemsayej21-Nov-07 23:01 
GeneralRe: another issue Pin
leflaco2-Jul-08 4:18
leflaco2-Jul-08 4:18 
GeneralWebParts Error - i cant understand Pin
basemsayej21-Nov-07 4:25
basemsayej21-Nov-07 4:25 
GeneralRe: WebParts Error - i cant understand Pin
Abdul Sami, PMP21-Nov-07 18:31
Abdul Sami, PMP21-Nov-07 18:31 
GeneralRe: WebParts Error - i cant understand Pin
basemsayej21-Nov-07 20:36
basemsayej21-Nov-07 20:36 
GeneralRe: WebParts Error - i cant understand Pin
Abdul Sami, PMP22-Nov-07 0:45
Abdul Sami, PMP22-Nov-07 0:45 
GeneralRe: WebParts Error - i cant understand Pin
basemsayej22-Nov-07 1:32
basemsayej22-Nov-07 1:32 
Questionhow to add ms flexigrid into web page in asp.net 2005? Pin
Khathar4-Jun-07 22:42
Khathar4-Jun-07 22:42 
GeneralError Using Error Mode - Part 2 Pin
broek48328-May-07 8:39
broek48328-May-07 8:39 

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

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