New Document
ASP.NET - Custom Controls

The new state management and postback features of ASP.NET are indeed very exciting. They provide developers with a whole new range of mechanisms for producing dynamic web pages. The ability to write your own custom controls takes that ability to a whole new level allowing you to write a control with custom functionality that can easily be reused in multiple pages by simply defining custom tags, similar to any other HTML element. The person implementing the layout for a page no longer needs to know all the details of how to write client-side code to get the dynamic behavior that has become so popular. However, there are some pitfalls that developers need to be aware of. ASP.NET promotes server-heavy designs. Network traffic can be dramatically increased as each client-side event can potentially cause a round trip to the server. Many of the effects that result from these frequent trips to the server can easily be accomplished with a few simple JavaScript functions. Calls to the server should be kept to a minimum, with as much being done on the client as possible. Using custom controls to generate client-side script we can take advantage of Dynamic HTML on the client while still providing a measure of separation between the layout and the logic.


ASP.Net allows the users to create controls. These user defined controls are categorized into:

  • User controls

  • Custom controls

User Controls:

Chapter 4 includes a chart of the five types of controls supported in ASP.NET: HTML controls, HTML server controls, web server controls, validation controls, and controls created by the developer. This chapter will discuss this last type of control, known as custom controls, and a subset of them called user controls.

Custom controls are compiled controls that act, from the client's perspective, much like web (ASP) controls. Custom controls can be created in one of three ways:

By deriving a new custom control from an existing control (e.g., deriving your own specialized text box from asp:textbox). This is known as a derived custom control.

By composing a new custom control out of two or more existing controls. This is known as a composite custom control.

By deriving from the base control class, thus creating a new custom control from scratch. This is known as a full custom control.

Of course, all three of these methods, and the three control types that correspond to them, are variations on the same theme. We'll consider these custom controls later in this chapter. The simplest category of custom controls is a subset called user controls. Microsoft distinguishes user controls as a special case because they are quite different from other types of custom controls. In short, user controls are segments of ASP.NET pages that can be reused from within other pages. This is similar to "include files" familiar to ASP developers. However, user controls are far more powerful. User controls support properties and events, and thus provide reusable functionality as well as reusable HTML.

User controls behaves like miniature ASP.Net pages, or web forms, which could be used by many other pages. These are derived from the System.Web.UI.UserControl class. These controls have the following characteristics.

<%@ Control %>
<hr>
<table>
  <tr>
      <td align="center">Copyright 2005 Liberty Associates, Inc.</td>
   </tr>
   <tr>
     <td align="center">Support at http://www.LibertyAssociates.com</td>  
   </tr>
</table>

  • They have an .ascx extension.

  • They may not contain any <html>, <body> or <form> tags.

  • They have a Control directive instead of a Page directive.

To understand the concept let us create a simple user control, which will work as footer for the web pages. To create and use the user control, take the following steps:

  • Create a new web application.

  • Right click on the project folder on the Solution Explorer and choose Add New Item.

Add New Item

Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially footer.ascx contains only a Control directive

<%@ Control Language="C#" AutoEventWireup="true" 
               CodeBehind="footer.ascx.cs" 
               Inherits="customcontroldemo.footer" %>

Add the following code to the file:

<table>
<tr>
<td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
</tr>
<tr>
<td align="center"> Location: Hyderabad, A.P </td>
</tr>
</table>

To add the user control to your web page, you must add the Register directive and an instance of the user control to the page. The following code shows the content file:

<%@ Page Language="C#" AutoEventWireup="true" 
         CodeBehind="Default.aspx.cs" 
         Inherits="customcontroldemo._Default" %>
<%@ Register Src="~/footer.ascx" 
             TagName="footer" TagPrefix="Tfooter" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" 
         Text="Welcome to ASP.Net Tutorials "></asp:Label>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" 
        onclick="Button1_Click"  Text="Copyright Info" />
        
       </div>
       <Tfooter:footer ID="footer1" runat="server" />
    </form>
</body>
</html>

When executed, the page shows the footer and this control could be used in all the pages of your site.

Custom Result

Observe the following:

(1): The Register directive specifies a tag name as well as tag prefix for the control.

<%@ Register Src="~/footer.ascx" TagName="footer" 
                                    TagPrefix="Tfooter" %>

(2): This tag name and prefix should be used while adding the user control on the page:

<Tfooter:footer ID="footer1" runat="server" />
Custom Controls:

Custom controls are deployed as individual assemblies. They are compiled into a dynamic link library (DLL) and used as any other ASP.Net server control. They could be created in either of the following way:

  • By deriving a custom control from an existing control

  • By composing a new custom control combing two or more existing controls

  • By deriving from the base control class

To understand the concept, let us create a custom control, which will simply render a text message on the browser. To create this control, take the following steps:

Create a new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer.

Solution Explorer

In the New Project dialog box, select ASP.Net Server Control from the project templates.

project templates

The above step adds a new project and creates a complete custom control to the solution, called ServerControl1. In this example, let us name the project CustomControls. To use this control, this must be added as a reference to the web site before registering it on a page. To add a reference to the existing project, right click on the project (not the solution), and click Add Reference.

Select the CustomControls project from the Projects tab of the Add Reference dialog box. The Solution Explorer should show the reference.

Custom Controls

To use the control on a page, add the Register directive just below the @Page directive:

<%@ Register Assembly="CustomControls"  
                Namespace="CustomControls" 
                TagPrefix="ccs" %>

Next you can use the control, like any other controls.

<form id="form1" runat="server">
    <div>
    <ccs:ServerControl1 runat="server" 
    Text = "I am a Custom Server Control" />
    </div> 
</form>

When executed the Text property of the control is rendered on the browser:

Custom Server Controls
Working with a Custom Control:

In the previous example, the value for the Text property of the custom control was set. ASP.Net added this property by default, when the control was created. The code behind file of the control will reveal this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
   [DefaultProperty("Text")]
   [ToolboxData("<{0}:ServerControl1 
                  runat=server></{0}:ServerControl1>")]
    public class ServerControl1 : WebControl
   {
      [Bindable(true)]
      [Category("Appearance")]
      [DefaultValue("")]
      [Localizable(true)]
      public string Text
      {
         get
         {
            String s = (String)ViewState["Text"];
            return ((s == null) ? "[" + this.ID + "]" : s);
         }
         set
         {
            ViewState["Text"] = value;
         }
      }
      protected override void RenderContents(
                                        HtmlTextWriter output)
      {
         output.Write(Text);
      }
   }
}

The above code is automatically generated for a custom control. Events and methods could be added to the custom control class.

Example:

Let us expand the previous custom control named SeverControl1. Let us give it a method named ‘checkpalindrome’, which will give it a power to check for palindromes.

Palindromes are words/literals that spell the same when reversed. We will consider simple words for this example.

Extend the code for the custom control, which should look as:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
   [DefaultProperty("Text")]
   [ToolboxData("<{0}:ServerControl1 
               runat=server></{0}:ServerControl1>")]
   public class ServerControl1 : WebControl
   {
      [Bindable(true)]
      [Category("Appearance")]
      [DefaultValue("")]
      [Localizable(true)]
      public string Text
      {
         get
         {
            String s = (String)ViewState["Text"];
            return ((s == null) ? "[" + this.ID + "]" : s);
         }
         set
         {
            ViewState["Text"] = value;
         }
     }
     protected override void RenderContents(
                                       HtmlTextWriter output)
     {
        if (this.checkpanlindrome())
        {
           output.Write("This is a palindrome: <br />");
           output.Write("<FONT size=5 color=Blue>");
           output.Write("<B>");
           output.Write(Text);
           output.Write("</B>");
           output.Write("</FONT>");
        }
        else
       {
          output.Write("This is not a palindrome: <br />");
          output.Write("<FONT size=5 color=red>");
          output.Write("<B>");
          output.Write(Text);
          output.Write("</B>");
          output.Write("</FONT>");
       }
    }
    protected bool checkpanlindrome()
    {
       if (this.Text != null)
       {
          String str = this.Text;
          String strtoupper = Text.ToUpper();
          char[] rev = strtoupper.ToCharArray();
          Array.Reverse(rev);
          String strrev = new String(rev);
          if (strtoupper == strrev)
          {
             return true;
          }
          else{
             return false;
          }
       }
       else
       {
          return false;
       }
    }
  }
}

When you change the code for the control, you must build the solution by clicking Build --> Build Solution, so that the changes are reflected in your project. Add a text box and a button control to the page, so that the user can provide a text, it is checked for palindrome, when the button is clicked.

<form id="form1" runat="server">
<div>
   Enter a word:
   <br />
   <asp:TextBox ID="TextBox1" runat="server" Width="198px">
   </asp:TextBox>
   <br />
   <br />
   <asp:Button ID="Button1" runat="server" 
               onclick="Button1_Click" 
               Text="Check Palindrome" Width="132px" />
   <br />
   <br />
   <ccs:ServerControl1 ID="ServerControl11" 
               runat="server" Text = "" />
</div>
</form>

The Click event handler for the button simply copies the text from the text box to the text property of the custom control.

protected void Button1_Click(object sender, EventArgs e)
{
     this.ServerControl11.Text = this.TextBox1.Text;
}

When executed, the control successfully checks palindromes.

checks palindromes

Observe the following:

(1) When you add a reference to the custom control, it is added to the toolbox and you can directly use it from the toolbox like any other control.

custom control reference

(2) The RenderContents method of the custom control class has been overridden here; you can add your own methods and events.

(3) The RenderContents method takes a parameter of HtmlTextWriter type, which is responsible for rendering on the browser.



Previous                                                                                                                                                       Next

Back to Top