Developing a Wonderful ASP.NET TextField Control

This article introduces you to the concept of the User Control. It also walks you through the development of a well-featured TextField control with several functionalities.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 11
March 14, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable zip file is available for this article.

The entire solution (source code) for this article is available as a free download in the form of a zip, as shown above. The source code in this article has been developed using Microsoft Visual Studio 2005 Professional Edition on Microsoft Windows Server 2003 Standard Edition. I didn't really test any of the code in any other tools/IDEs/servers/editions/versions. If you have any problems, please feel free to post in the discussion area.

Introduction

ASP.NET contains a control framework that is used by developers to create different user interfaces for their web applications. This framework is often referred to as web forms. The controls related to web forms are generally termed server controls.

The server control architecture is extensible; component developers design and implement new server controls. These new server controls are categorized into "User Controls" and "Custom Controls." Any of these controls are generally the extensions of existing server controls or extensions to the "Control" base class. Each of these controls gets converted to HTML tags at run time. This hides all the complexities and inconsistencies of any browser used for browsing the web application.

Several of these controls are made up of different properties, methods and events. These controls may also use "View State" to manage the state of server controls across individual web requests. Managing the state can be understood as "remembering the values or choices of the user across multiple requests of several pages."

Coming to the difference between a "User Control" and a "Custom Control," a "User Control" simply behaves like an include file with an ASCX extension. User controls are little more than a snippet of a web page that can be dragged and dropped onto the same web page for any number of times. They can be easily reused across any number of pages.

A "Custom Control" is a compiled code component and a lot more than a user control. A custom control is more complex to create when compared to a user control. When developing a custom control, you take hold of the control completely for both design time and run time execution. It gives you WYSISWYG features along with design time customization. You may have to emit lot of HTML and JavaScript depending upon the flavors of the features you require.

I already contributed a few articles on developing different types of custom controls on this same web site. You can have a look at http://www.aspfree.com/cp/bio/Jagadish-Chatarji.

Developing your own flexible Textbox control with new features: identifying requirements

In this section, I would like to introduce a new textbox control called "uctTextField." The "uct" stands for "User Control" as part of my naming convention. Let us consider the features not available with the existing Textbox server control (which is available as part of the ASP.NET framework).

  • It doesn't support labeling. You may have to add another label control to support the existing Textbox control.
  • To maintain some gap between Label and Textbox, you may have to work with TABLEs in HTML.
  • It doesn't have the "required input" option. You may have to add RequiredFieldValidator to the same Textbox control separately.
  • It doesn't have support for hints. Hints (or messages of format, etc.) are generally used when inputting dates and other items. You may have to add another Label control to support the same.
  • If I disable the Textbox, it simply locks the user out of the Textbox. But it doesn't automatically convert to Label (when in disabled mode).

At the moment, I feel that these features are frequently used in every application. Now imagine what would happen if I have five textboxes on the web page. I have to create five labels, validators, hint labels, and read-only labels, working with layout and more. You may want to be able to implement your own features instead of (or in addition to) the ones I've described here. This scenario is always boring for any ASP.NET developer.

To solve these "boring" problems, to a certain extent (or even to the full extent sometimes), user controls would be a great help. Now, I would like to design and develop a user control (called "uctTextField") supporting all of the above features. Once the control is developed, it can be dragged and dropped onto the web page any number of times, and it really improves my productivity.

Developing your own flexible Textbox control with new features: the beginning

Once you know the requirements for creating a new user control, it is time to implement the user control as part of your ASP.NET web solution. Using the Solution Explorer, right click on your solution and choose Add New Item. Within the Add New Item dialog box, select Web User Control as the template, provide the name of the User Control as "uctTextField" and hit Add.

Drag and drop the controls (and other stuff) onto your user control, so that it looks likes the following in the source mode:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="uctTextField.ascx.vb" Inherits="uctTextField" %>
<asp:Panel ID="pnlControl" runat="server">
<table cellpadding="0" cellspacing="0" border="0">
 
<tr valign="top">
   
<td style="white-space: nowrap">
     
<asp:Panel ID="pnlText" runat="server" Visible="false"
HorizontalAlign="Right">
       
<asp:Label ID="lblText" runat="server" >Label:</asp:Label>
     
</asp:Panel>
   
</td>
   
<td>
     
<asp:Label ID="lblControl" runat="server" Width=""
Visible="false"></asp:Label>
     
<asp:TextBox ID="txtControl" runat="server"></asp:TextBox>
      <
span
id="spnRequiredIndicator" runat="server"
class="requiredastrisk" visible="false">*</span>
      <
asp:Panel ID="pnlHint" runat="server" Visible="false"
HorizontalAlign="Left">
        <asp:Label ID="lblHint" runat="server" ></asp:Label>
     
</asp:Panel>
    
</td>
  
</tr>
</table>
<asp:RequiredFieldValidator ID="reqfValidator" runat="server"
ErrorMessage="[*name*] is required." ControlToValidate="txtControl"
Display="None" Enabled="false"></asp:RequiredFieldValidator>
</
asp:Panel>

According to the above source, you can understand that the entire control is a part of the Panel control. Within the panel, I created a simple HTML table to lay out all the controls in a convenient manner. The control mainly contains three Label controls, one Textbox control and one RequiredFieldValidator. For my convenience in layout, I added two more panels within the HTML table. The layout should look like the following in design mode (Fig 01).

Developing your own flexible Textbox control with new features: the skeleton

Once the design is completed, we need to start coding. In the code behind, I followed the skeleton shown below:

Imports System.ComponentModel

<ControlValueProperty("Text"), _
 
ValidationProperty("Text")> _
Partial Class uctTextField
 
Inherits System.Web.UI.UserControl
.
.
#Region "Page Events"
.
.
 
Public Overrides Sub Focus()

  Public Property Text() As String
 
Public Property MaxLength() As Integer
 
Public Property ErrorText() As String
 
Public Property Editable() As Boolean
 
Public Property Required() As Boolean
 
Public Property LabelTextValue() As String
 
Public Property LabelTextAlign() As
 
Public Property LabelTextVisible() As Boolean
 
Public Property LabelTextWidth() As System.Web.UI.WebControls.Unit
 
Public Property AutoPostBack() As Boolean
 
Public Property CssClassTextBoxControl() As String
 
Public Property CssClassLabelControl() As String
 
Public Property CssClassLabelText() As String
 
Public Property Tooltip() As String
 
Public Property ValidationGroup() As String
 
Public Property HintMessage() As String
 
Public Property HintMessageVisible() As Boolean
 
Public Event TextChanged As EventHandler
.
.

End Class

I removed the code for clarity. Based on the discussion of the requirements in previous sections, I came up with the above list of properties, methods and events. You can modify the properties according to your naming conventions and standards. My intention is just to give you an idea of the list of features of the user control.

Developing your own flexible Textbox control with new features: coding events

I am currently using Page Events to simply maintain ViewState. The code is as follows:

#Region "Page Events" 

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
   
If IsPostBack Then
     
Me.ErrorText = ViewState("ErrorText")
     
Required = ViewState("Required")
   
End If
 
End Sub

 Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.PreRender
 
ViewState("ErrorText") = ErrorText
 
ViewState("Required") = Required
End Sub

#End Region

The only method I used is the Focus method. When the control receives the focus, the cursor should be available in the text box. If the control is in read-only mode, it will not be able to receive any focus. It is defined as follows:

Public Overrides Sub Focus()
 
If Editable Then txtControl.Focus()
End Sub

Our control should also be supporting TextChanged event, and I created it as follows:

#Region "Events"
 
Public Event TextChanged As EventHandler
 
Protected Sub txtControl_TextChanged(ByVal sender As Object, ByVal e As
System.EventArgs) Handles txtControl.TextChanged
   
Me.Text = txtControl.Text
   
RaiseEvent TextChanged(sender, e)
 
End Sub
#End Region

Developing your own flexible Textbox control with new features: coding properties

The coding for the properties is very simple and easy to understand. The following is the entire code for all the properties mentioned in the skeleton:

 

<EditorBrowsable(EditorBrowsableState.Always), _
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), _
Bindable(True), Browsable(True), Category("Common")> _
 
Public Property Text() As String
   
Get
     
Return Me.txtControl.Text
   
End Get
   
Set(ByVal Value As String)
     
Me.txtControl.Text = Value
     
Me.lblControl.Text = Value
   
End Set
 
End Property

  <Category("Common")> _
 
Public Property MaxLength() As Integer
   
Get
     
Return Me.txtControl.MaxLength
   
End Get
   
Set(ByVal value As Integer)
     
Me.txtControl.Columns = value
     
Me.txtControl.MaxLength = value
   
End Set
 
End Property

  <Category("Common")> _
 
Public Property ErrorText() As String
   
Get
     
Return m_strErrorText
   
End Get
   
Set(ByVal Value As String)
     
Me.reqfValidator.ErrorMessage = Value & " is required."
     
m_strErrorText = Value
   
End Set
 
End Property

  <Category("Common")> _
 
Public Property Editable() As Boolean
   
Get
     
Return Me.txtControl.Visible
   
End Get
   
Set(ByVal Value As Boolean)
     
If Editable <> Value Then
       
If Editable Then
         
lblControl.Text = Me.txtControl.Text
       
End If
       
lblControl.Visible = Not Value
       
txtControl.Visible = Value
       
reqfValidator.Enabled = Value And Required
       
spnRequiredIndicator.Visible = Value And Required
     
End If
   
End Set
 
End Property

  <Category("Common")> _
 
Public Property Required() As Boolean
   
Get
     
Return m_blnRequired
   
End Get
   
Set(ByVal Value As Boolean)
     
reqfValidator.Enabled = Editable And Value
     
spnRequiredIndicator.Visible = Editable And Value
     
m_blnRequired = Value
   
End Set
 
End Property

  <Category("Field Text")> _
 
Public Property LabelTextValue() As String
   
Get
     
Return Me.lblText.Text
   
End Get
   
Set(ByVal value As String)
     
Me.lblText.Text = value
   
End Set
 
End Property

  <Category("Field Text")> _
 
Public Property LabelTextAlign() As System.Web.UI.WebControls.HorizontalAlign
   
Get
      
Return pnlText.HorizontalAlign
   
End Get
   
Set(ByVal Value As System.Web.UI.WebControls.HorizontalAlign)
     
pnlText.HorizontalAlign = Value
   
End Set
 
End Property

  <Category("Field Text")> _
 
Public Property LabelTextVisible() As Boolean
   
Get
     
Return Me.pnlText.Visible
   
End Get
   
Set(ByVal Value As Boolean)
     
Me.pnlText.Visible = Value
   
End Set
 
End Property

  <Category("Field Text")> _
 
Public Property LabelTextWidth() As System.Web.UI.WebControls.Unit|
   
Get
     
Return pnlText.Width
   
End Get
   
Set(ByVal Value As System.Web.UI.WebControls.Unit)
     
pnlText.Width = Value
   
End Set
 
End Property

Developing your own flexible Textbox control with new features: coding properties continued

The following is the continuation of the previous section for the entire code for all of the properties mentioned in the skeleton:

  Public Property AutoPostBack() As Boolean
   
Get
     
Return txtControl.AutoPostBack()
   
End Get
   
Set(ByVal Value As Boolean)
     
txtControl.AutoPostBack = Value
   
End Set
 
End Property

  <Category("Appearance")> _
 
Public Property CssClassTextBoxControl() As String
   
Get
     
Return txtControl.CssClass
   
End Get
   
Set(ByVal Value As String)
     
txtControl.CssClass = Value
   
End Set
 
End Property

  <Category("Appearance")> _
 
Public Property CssClassLabelControl() As String
   
Get
     
Return Me.lblControl.CssClass
   
End Get
   
Set(ByVal value As String)
     
Me.lblControl.CssClass = value
   
End Set
 
End Property

  <Category("Appearance")> _
 
Public Property CssClassLabelText() As String
   
Get
     
Return Me.lblText.CssClass
   
End Get
   
Set(ByVal value As String)
     
Me.lblText.CssClass = value
   
End Set
 
End Property

  <Category("Appearance")> _
  
Public Property Tooltip() As String
   
Get
     
Return pnlControl.ToolTip
   
End Get
   
Set(ByVal Value As String)
     
pnlControl.ToolTip = Value
   
End Set
 
End Property

  Public Property ValidationGroup() As String
   
Get
     
Return Me.txtControl.ValidationGroup
   
End Get
   
Set(ByVal value As String)
     
Me.txtControl.ValidationGroup = value
     
Me.reqfValidator.ValidationGroup = value
   
End Set
 
End Property

  Public Property HintMessage() As String
   
Get
     
Return Me.lblHint.Text
   
End Get
   
Set(ByVal value As String)
     
Me.lblHint.Text = value
   
End Set
 
End Property

  Public Property HintMessageVisible() As Boolean
   
Get
     
Return Me.pnlHint.Visible
   
End Get
   
Set(ByVal value As Boolean)
     
Me.pnlHint.Visible = value
   
End Set
 
End Property

I hope you enjoyed this article. Any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials