Click here to Skip to main content
Email Password   helpLost your password?

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!

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralError rendering Control
amirmuthu
1:54 13 Dec '07  
hi,
i have created the ddl file using your code. but it raises the error is called "Error rendering control" when i drag and drop to the form.

Please advice
Regards,
Muthu
GeneralRequired Field Validator not rendering
UAWildcat
16:06 17 Jul '07  
Hello,

I created a custom server control very similar to the control in the article. I also set the Text property of the required field validator but it does not show up.

I have tried using the custom textbox on a page by itself and on a page with a validation summary object.

The error message displayed correctly on the page with the validation summary, but the text property did not. I set the text property programmatically within the custom control to display an asterisk beside the textbox.

Has anyone else encountered this behavior?

Thanks,

Mike Confused
QuestionDropdownlist does not allow child controls
sandeepsm
19:55 22 Jan '07  
A problem when creating a custom web control which contains a DropDownList and a RequiredFieldValidator in one.



QuestionRound Trip
gooseman
3:03 15 Nov '06  
Is there anyway I can have this be Dynamic and set the EnableClientScript to true? My business requirements demand that it does not "round trip".

Thanks,
Chris
GeneralProblem on Re-Load (Post Back)
ashque01
14:03 3 Nov '05  
I added a property to text box, say CurrencyValue. This property is assigned value ="A" in OnInit method as given in sample. After it raises an event and does a postback, I change that property to "B". But when it loads up, it again runs OnInit method and initialises that property to "A" for that control. Is there a way I could check for the postback and do nothing in OnInit method if its a postback. Please help


GeneralRe: Problem on Re-Load (Post Back)
BishoyAtef
14:20 17 Jan '06  
try if (!Page.IsPostBack)
GeneralCreate this Control Dynamically
anilkumarJJR
5:56 29 Aug '05  
I have implemented this code and this works Great ? The way I would want to implement the is to create the component dynamically.I have registered the assembly in the HTML page and also i have commented the line of code as given below

NOTE I HAVE COMENTED THE LINE OF CODE <WImdows:RequiredTextBox runat="server"id="txtname" InvalidMessage ="*" clientScript="false"/> in the HTML page.

And then this code is written in Page_Load

RequiredTextBox1 nTbox = new RequiredTextBox1();
Controls.Add(nTbox);

It gives and ERROR saying that control has to be in the FORM tag.
Question is WILL SUCH a kind of approach feasible .. I have seen some examples in most of them on composite control and there rendering behaviour any Thoughts?
GeneralFields not visible
Anonymous
11:02 1 Jul '04  
I've created controls using ASP.NET. But when I run it - it is not visble in the browser. Is there any setting I should change ??
Generaldif. projects
oscarnmp
7:10 2 Jan '04  
Through the VS compiler and with 2 dif. projects, one for the wcc and other for the web form, how can I put everything to work together?

Thank you,

Oscar Pereira
GeneralA problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one
chhchhstock
5:51 4 Dec '03  
Hi,

I have a problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one. I referenced the article “Building an ASP.NET custom web control: a textbox and validator in one” from Wim Hollebrandse to build my custom control.

The partial code is below:

public class LabelRadioButtonList : RadioButtonList
{
private RadioButtonList internal_RadioButtonList;
private RequiredFieldValidator req;
public string InvalidMessage;
public string ClientScript="true";

protected override void CreateChildControls()
{
internal_RadioButtonList = new RadioButtonList();
// process all items to the RadioButtonList object
. . .
this.Controls.Add(internal_RadioButtonList);

//Process req and add it to the composite control
// LabelRadioButtonList
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = this.InvalidMessage;
req.EnableClientScript=(this.ClientScript.ToLower()!="false");
this.Controls.Add(req);
}

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

Error:

Exception Details: System.Web.HttpException: Unable to find control id 'LabelRadioButtonList1' referenced by the 'ControlToValidate' property of ''.

Source Error:

Line 750: internal_RadioButtonList.RenderControl(writer);
Line 751: req.RenderControl(writer);
Line 752: base.Render(writer);
Line 753: }


Source File: c:\inetpub\wwwroot\classlibrary\customcontrols\webcustomcontrol1.cs Line: 751

So, the error occurs on the line 751 – req.RenderControl(writer); It seems that the validator cannot find the object LabelRadioButtonList, which actually contains this validator.

I have no problem to build a custom control containing a TextBox and a validator. However, error is produced when creating the custom control mentioned above. It would be very appreciated if you have any comment.

Stock
GeneralRe: A problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one
Dusan Musak
6:35 12 Nov '04  
try this:

protected override void OnInit(EventArgs e) {
.....
....
Controls.Parent.Add(req);
}
GeneralA problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one
Anonymous
5:31 4 Dec '03  
Hi,

I have a problem when creating a custom web control which contains a RadioButtonList and a RequiredFieldValidator in one. I referenced the article “Building an ASP.NET custom web control: a textbox and validator in one” from Wim Hollebrandse to build my custom control.

The partial code is below:

public class LabelRadioButtonList : RadioButtonList
{
private RadioButtonList internal_RadioButtonList;
private RequiredFieldValidator req;
public string InvalidMessage;
public string ClientScript="true";

protected override void CreateChildControls()
{
internal_RadioButtonList = new RadioButtonList();
// process all items to the RadioButtonList object
. . .
this.Controls.Add(internal_RadioButtonList);

//Process req and add it to the composite control
// LabelRadioButtonList
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = this.InvalidMessage;
req.EnableClientScript=(this.ClientScript.ToLower()!="false");
this.Controls.Add(req);
}

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

Error:

Exception Details: System.Web.HttpException: Unable to find control id 'LabelRadioButtonList1' referenced by the 'ControlToValidate' property of ''.

Source Error:

Line 750: internal_RadioButtonList.RenderControl(writer);
Line 751: req.RenderControl(writer);
Line 752: base.Render(writer);
Line 753: }


Source File: c:\inetpub\wwwroot\classlibrary\customcontrols\webcustomcontrol1.cs Line: 751

So, the error occurs on the line 751 – req.RenderControl(writer); It seems that the validator cannot find the object LabelRadioButtonList, which actually contains this validator.

I have no problem to build a custom control containing a TextBox and a validator. However, error is produced when creating the custom control mentioned above. It would be very appreciated if you have any comment.

Pat

Generalput image inside the validator
abiezer
12:42 16 Sep '03  
how can i put a image inside of validator control??

thanks
GeneralImage not visible
MStanbrook
3:31 13 Aug '02  
It might just be me, but the screenshot image isn't visible in the article.


Mike Stanbrook
mstanbrook@yahoo.com
GeneralRe: Image not visible
Anonymous
19:52 19 Nov '03  
It's just you


Last Updated 13 Aug 2002 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010