Click here to Skip to main content
Click here to Skip to main content

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

, 12 Aug 2002
Rate this:
Please Sign up or sign in to vote.
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.
<!-- Download Links --> <!-- Add the rest of your HTML here -->

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.

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:

<%@ 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:

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

About the Author

Wim Hollebrandse
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 Pinmembershabari717-Jan-13 0:09 
GeneralMy vote of 4 Pinmemberkiran shettar30-Nov-12 20:41 
GeneralMy vote of 1 PinmemberNaveenMupalla4-Jul-12 22:59 
GeneralMy vote of 1 Pinmembersandeepbs4041-Oct-11 1:50 
GeneralError rendering Control Pinmemberamirmuthu13-Dec-07 0:54 
GeneralRequired Field Validator not rendering PinmemberUAWildcat17-Jul-07 15:06 
QuestionDropdownlist does not allow child controls Pinmembersandeepsm22-Jan-07 18:55 
QuestionRound Trip Pinmembergooseman15-Nov-06 2:03 
GeneralProblem on Re-Load (Post Back) Pinmemberashque013-Nov-05 13:03 
GeneralRe: Problem on Re-Load (Post Back) PinmemberBishoyAtef17-Jan-06 13:20 
GeneralCreate this Control Dynamically PinmemberanilkumarJJR29-Aug-05 4:56 
GeneralFields not visible PinsussAnonymous1-Jul-04 10:02 
Generaldif. projects Pinmemberoscarnmp2-Jan-04 6:10 
GeneralA problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one Pinmemberchhchhstock4-Dec-03 4:51 
GeneralRe: A problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one PinsussDusan Musak12-Nov-04 5:35 
GeneralA problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one PinsussAnonymous4-Dec-03 4:31 
Generalput image inside the validator Pinmemberabiezer16-Sep-03 11:42 
GeneralImage not visible PinmemberMStanbrook13-Aug-02 2:31 
GeneralRe: Image not visible PinsussAnonymous19-Nov-03 18:52 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 13 Aug 2002
Article Copyright 2002 by Wim Hollebrandse
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid