Published: 13 Jul 2007
By: Granville Barnett
Download Sample Code

In this - the first of many parts - we will look at what a custom control is and how it differs from user controls, as well as classes that our custom controls can derive from. In the article we will also implement a simple custom control.

User Controls

The composition of a user control is very simple and requires a smaller skill set than that required by custom control developers. User controls preserve the use of ASP.NET mark-up coupled with the code behind model (although inline code is an option).

One of the great things about user controls is that they allow a quick conversion from something like an existing ASP.NET page to a user control - and as a result they have many similarities. Some of the similarities include the use of existing server controls that ASP.NET offers, as well as the event model that you are familiar with as ASP.NET developers. User controls provide a quick and easy way to introduce modularity into an ASP.NET web application.

User controls - unlike ASP.NET pages that have the file extension .aspx - have the extension .ascx. User controls files cannot be requested via a browser; they can only be used via the containing ASP.NET page. Web servers like IIS and Cassini prohibit browsing to files with the .ascx file extension.

Like ASP.NET pages - in the context of a file based web site - compilation of a user control is done upon first request.

So why after this glowing review should we even care about custom control development in ASP.NET? Custom controls allow us a more atomic control on authoring, as well as the ability to ship our controls as a dynamic link library (.dll) which can be pre-compiled as well as integrating nicely with the Visual Studio IDE.

If you are building controls specifically for a certain web application, then user controls will probably be all you need. However, if your desire is to build redistributable controls that integrate well with the Visual Studio IDE, then custom controls are the best choice.

User Control example

Even if the main purpose of this article is covering custom controls, I would like to start with a walkthrough about the creation of a simple user control.

In the following example, I have identified a component that will appear many times within my hypothetical web site. The user control that we will create simply consists of a GridView and a SqlDataSource that queries for all the ContactName's and CompanyName's from the Northwind Customers table.

When creating user controls I like to create a new folder within my web site entitled... yes you guessed it, UserControls; and drop all my user controls into that folder. However, this isn't a requirement.

Step 1: Adding a user control to the web site

Adding a user control to your solution is real simple. You just have to right click your solution and click Add New Item; then from the dialog window click Web User Control and name the control MyUserControl.ascx.

Figure 1: Adding a Web User Control

cc1.png

Step 2: Adding the ASP.NET controls to MyUserControl.ascx

As mentioned earlier this user control will merely consist of a GridView and a SqlDataSource ASP.NET server controls.

Before we go ahead and add our controls to the user control, notice that the Page directive is not used for our user control, and that it has been replaced with the Control directive.

Listing 1: Control directive

As well as the Control directive also note that our code behind derives from the System.Web.UI.UserControl class and not from System.Web.UI.Page.

Listing 2: Deriving from the UserControl class

There is only one similarity between the System.Web.UI.UserControl and System.Web.UI.Page types: they both derive from TemplateControl.

Let's go ahead and add the required server controls to our user control.

Listing 3: Adding a GridView and SqlDataSource server control to our user control

Listing 1-1 shows the final version of MyUserControl.ascx.

Step 3: Adding our user control to a Web Form

There are a few ways in which we can do this. We can either use the Register directive, or we can go ahead and register our user control in the web.config.

Using the Register directive is really simple and allows all web forms with the appropriate Register directive to go ahead and use our user control. Setting up the Register directive is easy. We need to provide a TagPrefix, TagName and Src for the user control – all of which are attributes of the Register directive.

Listing 4: Setting up the Register directive

As well as using the Register directive, as of ASP.NET 2.0, we can go ahead and register our user control within the controls element of the pages element.

Listing 5: Registering our use control in the web.config

When registering our user control in the web.config file, all pages within the web site can now use the user control omitting the Register directive.

Step 4: Using our simple user control within a Web Form

This is really simple. Either setup the Register directive on your Web Form or register your user control within the web.config as shown in step 3. With that done, you will be able to use your control as shown in the following listing.

Listing 6: Using our user control within a Web Form

There are a few things to remember about user controls. The first is that you shouldn't include a server form element, which is a form control with the runat="server" attribute. However, you can use a standard form element. Also, you should not include any HTML elements that are already contained in the Web Form, like body, head and so on. If you require either, a MasterPage might be better suited for your needs.

Figure 2: Our simple user control in action

cc2.png

Custom Controls

The power of custom controls is staggering. You can create highly complex controls and then bundle them up and ship them as compiled managed .dlls. As I mentioned before, custom controls can provide a richer interface between the developer and the control, via the Visual Studio IDE. This is achieved using attributes to decorate various parts of a custom controls internals.

When creating a custom control, we derive our control class from one of two base types:

  • System.Web.UI.Control
  • System.Web.UI.WebControl

Control

Deriving from the Control class allows our control to take advantage of the rendering methods provided by the Control class, as well as the use of ViewState.

WebControl

The WebControl class derives from the Control class. However, if we derive our custom control from WebControl, we get free support for many visual aspects of our control, like font size, CSS classes, background colour and so on.

Which class should I derive from?

When you are creating a custom control that requires little or no UI, then you should derive from the Control class. If your control does require the need for extensive UI support, then you should derive from WebControl.

Creating a simple custom control

In this first part of the series we will create a trivial Label-like control that simply allows the user to define the text of a server control. This control will derive from the Control class.

Step 1: Creating a new Web Control Library project

Right click on your web site solution and click on the Add New Project. From the dialog window, choose the Web Control Library project template. You can name this project whatever you want.

Figure 3: Creating a new Web Control Library project

cc3.png

Step 2: Deriving from the Control class

Go ahead and add a new class to your Web Control Library called SimpleLabel, and derive SimpleLabel from the System.Web.UI.Control class.

Listing 7: Deriving from Control

Step 3: Adding some functionality to our control

In this step we will override the Render method defined in the Control class, and also add a Text property to the class so that our user can define the text of our label.

First, we will add the Text property to our class and store the value in ViewState so the control can maintain state over post back.

Note: ViewState will be described in detail in the next part of this series.

Listing 8: Text property

Now we will go ahead and override the Render method of our control.

Listing 9: Overriding the Render method

In the previous listing, we start off by writing an opening tag, then writing out the user defined text and then finally closing that opening tag.

Note: We will discuss the control lifecycle in the next part along with rendering.

Listing 10: Our final control

Please go ahead now and build the project.

Step 4: Using the SimpleLabel custom control within an ASP.NET project

You have two choices here: Either install the resulting .dll into the global assembly cache (GAC) or drop the .dll into the bin folder of your web application. We will do the latter.

Right click on your web site solution and click Add Reference, a dialog window will appear. Click on the Browse tab and then browse to the resulting .dll created from the web control library project.

Figure 4: Referencing our web control library project

cc4.png

With the .dll reference you can either use the Control directive to register your custom controls, or you can use the web.config file to do so. I will use the web.config to register my control. If you want to use the Control directive please check the beginning of this article.

Listing 11: Registering the web control library

With our control library registered we can now go ahead and use it!

Listing 12: Using our control within a Web Form

Figure 5: Our custom control in all of its glory

cc5.png

If you view the source of the resulting HTML then you will see that Granville is a child of the element, which is how we defined our control in the Render method.

Summary

Hopefully I have introduced you gently to the world of custom control development. In future parts of this series we will look at the more advanced features of custom control development, and the design considerations that we must take into account.

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Granville Barnett

Sorry, no bio is available

This author has published 32 articles on DotNetSlackers. View other articles or the complete profile here.

Other articles in this category


Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.

You might also be interested in the following related blog posts


Introducing RadScrollablePanel for Windows Forms read more
Introducing SharePoint 2010 Training at U2U read more
Using WCF with SQL Azure and Telerik OpenAccess read more
The Underground at PDC read more
New content providers for the RadEditor and RadFileExplorer controls read more
The ESRI Dev Summit 2010 hosted in Palms Springs CA is open for registration. read more
MVC or Web Forms? A Dying Question read more
Designer Support for One-Way navigations in Entity Framework 4 read more
How to display data from different tables using one data source read more
Visual Studio 2010 Extension Manager read more
Top
 
 
 

Discussion


Subject Author Date
placeholder Where is the library? Fred Ewing 5/7/2009 4:44 PM
Thx! Pedro Pereira 11/29/2011 8:38 AM
placeholder Thanks Sunny Paaji 1/30/2013 2:39 PM

Please login to rate or to leave a comment.