Subscribe

RSS Feed (xml)

Creating a Composite 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 AspNetPublic Class EmailTextBox
Inherits System.Web.UI.WebControls.WebControl
Implements INamingContainer
Private textBox As textBox
Private validator As RegularExpressionValidator
Public Property Text() As String
Get
EnsureChildControls()
Return textBox.Text
End Get
Set(ByVal Value As String)
EnsureChildControls()
textBox.Text = Value
End Set
End Property
Public Property ErrorMessage() As String
Get
EnsureChildControls()
Return validator.ErrorMessage
End Get
Set(ByVal Value As String)
EnsureChildControls()
validator.ErrorMessage = Value
End Set
End Property
Public Overrides ReadOnly Property Controls() As ControlCollection
Get
EnsureChildControls()
Return MyBase.Controls
End Get
End Property
Protected Overrides Sub CreateChildControls()
Controls.Clear()
textBox = New TextBox
validator = New RegularExpressionValidator
Controls.Add(textBox)
Controls.Add(validator)
textBox.ID = “Email1”
validator.ControlToValidate = textBox.ID
‘A typical email address regular expression
validator.ValidationExpression = “^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}
\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))
([a-zA-Z]{2,4}|[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=”AspNet” Namespace=”AspNet”
Assembly=”AspNet” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” >
<html>
<head>
<title>code0304</title>
</head>
<body>
<form id=”Form1” method=”post” runat=”server”>
<AspNet:EmailTextBox
ID=”EmailTextBox1”
ErrorMessage=”You must provide a valid email address!”
runat=”server”
/>
</form>
</body>
</html>

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.

No comments:

Archives

Variety in the Web World