11.3. Creating a Custom Web Part

Problem

You need some functionality for your web parts that you cannot get with user controls or standard ASP.NET server controls, such as the ability to build them into a separate assembly for sharing with other applications.

Solution

Create a class that inherits from the WebPart class and implements the required functionality. Then, use the class with the Web Part control set in the same manner as you would other controls.

Use the .NET language of your choice to:

  1. Create a new class inheriting from the WebPart class.

  2. Override the CreateChildControls method and create the controls required for the web part.

Use the custom web part with the Web Part control set in the same manner as you would any other control (see Recipe 11.1 for details).

The application we have implemented to demonstrate the solution is shown in Examples 11-12, 11-13, 11-14, 11-15 through 11-16. Examples 11-12 (VB) and 11-13 (C#) show the class to implement the custom web part. Examples 11-14, 11-15 through 11-16 show the .aspx and code-behind for a page that demonstrates using the custom web part.

Discussion

For most applications, user controls and standard ASP.NET server controls provide the best option for use as web parts. The primary reasons are their reusability and, in the case of user controls, the efficiency of developing them. On the other hand, developing custom web parts is akin to developing custom server controls (see Chapter 6). Since the entire user interface is generated ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.