Click here to Skip to main content
15,886,258 members
Articles / Web Development / ASP.NET
Article

Building an ASP.NET custom web control: a textbox and validator in one

Rate me:
Please Sign up or sign in to vote.
4.58/5 (30 votes)
12 Aug 20023 min read 292.7K   3.8K   59   19
In this article we will have a look at implementing a custom web control. This web control will inherit from the TextBox web control, and will automatically add a required field validator at run-time.

Introduction

In this article we will have a look at implementing a custom web control. This web control will inherit from the TextBox web control, and will automatically add a required field validator at run-time. This way, when we need a required field text box, we don't need to mess about with the required field validator, but instead we just define an instance of our custom web control.

Class definition

The class definition for our web control is quite straightforward. Since we want to create a TextBox control, we will inherit from the TextBox class. This means we will still be able to use all of the existing attributes which are defined for the TexBox - after all, we want a texbox as the basis with a required field validator 'embedded'. Let's have a look at our code-behind file for our RequiredTextBox control.

C#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WimdowsControls.Web.UI {
  public class RequiredTextBox : TextBox {
    private  RequiredFieldValidator req;
    public string InvalidMessage;
    public string ClientScript="true";

    protected override void OnInit(EventArgs e) {
      req = new RequiredFieldValidator();
      req.ControlToValidate = this.ID;
      req.ErrorMessage = this.InvalidMessage;
      req.EnableClientScript = (this.ClientScript.ToLower()!="false");
      Controls.Add(req);
    }

    protected override void Render(HtmlTextWriter w) {
      base.Render(w);
      req.RenderControl(w);
    }
  }
}

As we can see, we define the class RequiredTextBox which inherits from the System.Web.UI.WebControls.TextBox class. Since our text box does not have any attributes like the ErrorMessage attribute of the RequiredFieldValidator, we need to define a public property for that. Note that we don’t necessarily need the get and set methods for the property here. Also, we define a ClientScript attribute which will map to the corresponding EnableClientScript attribute of the validator control. The OnInit method is a method we need to override, so we can explicitly add (by using the Controls.Add method) the required field validator control to our TextBox control. Also, we will have to override the Render method which renders the HTML to the browser. By calling base.Render() method, we call the Render method on our base class, in our case the TextBox class. In addition to that we need to render the HTML code for our RequiredFieldValidator control by calling its RenderControl method. We now need to compile this into an assembly. Using the C# compiler, we use the following command (assuming the directory is our virtual directory where our .aspx and code behind file are located):

csc /out:bin\wimdowscontrols.dll /target:library /r:system.dll wimdowscontrols.cs

Now, let's see what our cool ASP.NET page looks like:

ASP.NET
<%@ Register TagPrefix="Wimdows" Namespace="WimdowsControls.Web.UI" 
             Assembly="WimdowsControls" %>

<form runat="server">
<Wimdows:RequiredTextBox runat="server" id="txtName" 
                         InvalidMessage="Name is required." 
                         ClientScript="false"/>
<br />
<asp:Button runat="server" id="btnSubmit" Text="Validate"/>
</form>

That's it! We need do need the Register directive to register our component, almost in the same way as we do with a user control. Whereas the user control would point to a Src .ascx file, we specifiy our namespace in which we declared our custom control and the physical assembly, the DLL. By using any TagPrefix, we can refer to our new custom control as <TagPrefix:ClassName>. Of course we need the runat=server attribute, and we specify some other attributes that our control supports. We're ready to roll! Let's give it a go! Our control should not use client validation, since we specified the ClientScript=false attribute. Here's the screenshot:

Image 1

You will notice that on the submit of the form, it will always perform a server round-trip, because we explicitly specified the ClientScript attribute value to false.

Conclusion  

In this article we've briefly seen how beneficial it can be to create your own composite custom control. Of course you can extend the sample by adding more controls, and more attributes - but I will leave that up to you. You know the basics now!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
Wim is a senior web developer who works for Register.com Corporate Services Europe. Wim has got over 6 years of web development experience, mainly using the following technologies: HTML, JScript, DHTML, ASP, COM, XML, XSLT, WML, SQL Server, Oracle, Transact SQL and more. Since the late beta 1 of the .NET framework, he's been exposed to working with ASP.NET, VB.NET, C# and XML web services. He is also the founder of Wimdows.net, an ASP.NET community site.

Comments and Discussions

 
GeneralMy vote of 1 Pin
PBGuy17-Jan-13 0:09
professionalPBGuy17-Jan-13 0:09 
GeneralMy vote of 4 Pin
kiran shettar30-Nov-12 20:41
kiran shettar30-Nov-12 20:41 
GeneralMy vote of 1 Pin
NaveenMupalla4-Jul-12 22:59
NaveenMupalla4-Jul-12 22:59 
GeneralMy vote of 1 Pin
sandeepbs4041-Oct-11 1:50
sandeepbs4041-Oct-11 1:50 
Not Helpful
GeneralError rendering Control Pin
amirmuthu13-Dec-07 0:54
amirmuthu13-Dec-07 0:54 
GeneralRequired Field Validator not rendering Pin
UAWildcat17-Jul-07 15:06
UAWildcat17-Jul-07 15:06 
QuestionDropdownlist does not allow child controls Pin
sandeepsm22-Jan-07 18:55
sandeepsm22-Jan-07 18:55 
QuestionRound Trip Pin
gooseman15-Nov-06 2:03
gooseman15-Nov-06 2:03 
GeneralProblem on Re-Load (Post Back) Pin
ashque013-Nov-05 13:03
ashque013-Nov-05 13:03 
GeneralRe: Problem on Re-Load (Post Back) Pin
BishoyAtef17-Jan-06 13:20
BishoyAtef17-Jan-06 13:20 
GeneralCreate this Control Dynamically Pin
anilkumarJJR29-Aug-05 4:56
anilkumarJJR29-Aug-05 4:56 
GeneralFields not visible Pin
Anonymous1-Jul-04 10:02
Anonymous1-Jul-04 10:02 
Generaldif. projects Pin
oscarnmp2-Jan-04 6:10
oscarnmp2-Jan-04 6:10 
GeneralA problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one Pin
chhchhstock4-Dec-03 4:51
chhchhstock4-Dec-03 4:51 
GeneralRe: A problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one Pin
Dusan Musak12-Nov-04 5:35
sussDusan Musak12-Nov-04 5:35 
GeneralA problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one Pin
Anonymous4-Dec-03 4:31
Anonymous4-Dec-03 4:31 
Generalput image inside the validator Pin
abiezer16-Sep-03 11:42
abiezer16-Sep-03 11:42 
GeneralImage not visible Pin
MStanbrook13-Aug-02 2:31
MStanbrook13-Aug-02 2:31 
GeneralRe: Image not visible Pin
Anonymous19-Nov-03 18:52
Anonymous19-Nov-03 18:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.