Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.4. Creating a Composite Control

You want to combine two or more Web Controls into a single composite custom control.


This example shows you how to create a very simple yet useful composite control. The control is a composition of a TextBox and a validator, and the control can be used to validate email addresses. The EmailTextBox class is as follows:

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports System.ComponentModel.Design

Namespace AspNetCookbook
 Public Class EmailTextBox
  Inherits System.Web.UI.WebControls.WebControl
  Implements INamingContainer

  Private textBox As textBox
  Private validator As RegularExpressionValidator

  Public Property Text() As String
    Return textBox.Text
   End Get
   Set(ByVal Value As String)
    textBox.Text = Value
   End Set
  End Property

  Public Property ErrorMessage() As String
    Return validator.ErrorMessage
   End Get
   Set(ByVal Value As String)
    validator.ErrorMessage = Value
   End Set
  End Property

  Public Overrides ReadOnly Property Controls() As ControlCollection
    Return MyBase.Controls
   End Get
  End Property

  Protected Overrides Sub CreateChildControls()

   textBox = New TextBox
   validator = New RegularExpressionValidator


   textBox.ID = "Email1"
   validator.ControlToValidate = textBox.ID
   'A typical email address regular expression
   validator.ValidationExpression = "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}
  End Sub
 End Class
End Namespace

To use this control, you need to do the following:

<%@ Page language="VB" %>
<%@ Register TagPrefix="AspNetCookbook" Namespace="AspNetCookbook" 
Assembly="AspNetCookbook" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 

<form id="Form1" method="post" runat="server">
  ErrorMessage="You must provide a valid email address!"



This control validates the input in the TextBox. If the input is not a valid email address an error message appears. Controls like this one are useful on pages that contain a lot of user input that needs to be validated. You can easily extend this control to use several validator types, allow the page developer to define his/her own validation expression, and so on.

See Also

Regular Expression Library—http://regexlib.com/

  • + Share This
  • 🔖 Save To Your Account