When you think ASP, think...
Recent Articles xml
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips
spgif spgif

Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
XML Info
Author an Article
spgif spgif
ASP ASP.NET ASP FAQs Feedback topnav-right
Print this page.
User Tips: Creating a Validation Control for CheckBoxLists

By Cenk Civici and Scott Mitchell

Creating CheckBox and CheckBoxList Validators in ASP.NET 2.0
This user tip examines creating a CheckBoxList validator in ASP.NET version 1.x. The code, as written, will work in ASP.NET version 2.0. However, there is an article here on 4Guys that examines how to create custom CheckBox and CheckBoxList validation controls, although it's done as an ASP.NET 2.0 server control. For more information, refer to Creating Validator Controls for the CheckBox and CheckBoxList.

One of the most useful and time-saving features of ASP.NET, when compared to classic ASP, are ASP.NET's validation controls. Validation controls are a set of server-side Web controls that developers can add to their ASP.NET Web pages to validate other Web controls. For example, the RequiredFieldValidator validation control can be placed on an ASP.NET Web page and set to validate a TextBox control. By simply adding this control, the developer can then quickly determine whether or not the user has entered a meaningful entry into the TextBox Web control by simply checking the Page.IsValid property. (For more information on ASP.NET's validation controls be sure to read: Form Validation with ASP.NET - It Doesn't Get Any Easier!)

One shortcoming of the RequiredFieldValidator control is that it only works for a subset of the Web controls. Per the documentation, for any validator control the "standard controls that can be validated are TextBox, ListBox, DropDownList, RadioButtonList, System.Web.UI.HtmlControls.HtmlInputText, System.Web.UI.HtmlControls.HtmlInputFile, System.Web.UI.HtmlControls.HtmlSelect and System.Web.UI.HtmlControls.HtmlTextArea." There are other useful ASP.NET Web controls, however, that you may wish to ensure contain a value. For example, RequiredFieldValidators do not work with the CheckBoxList Web controls. (CheckBoxLists present a list of grouped check boxes for the user to select one or more checkboxes from.) If you specify a RequiredFieldValidator's ControlToValidate property to the ID of a CheckBoxList Web control you will get an exception informing you that the CheckBoxList cannot be validated.

There are clearly times when we'd like to ensure that the user has selected at least one checkbox from the checkbox list. Ideally we'd like to be able to add a RequiredFieldValidator to the ASP.NET Web page and set its ControlToValidate property to the ID of the CheckBoxList Web control we'd like to validate, but, as aforementioned, this will raise an exception. In this tip we'll examine how to build a custom ASP.NET server control that can be used in place of a RequiredFieldValidator for CheckBoxList Web controls.

How to Overcome any Shortcoming
Now that we've identified a problem with one of the ASP.NET Web controls, how can we overcome it? The nice thing with ASP.NET is that you can simply create a new custom Web control that includes the desired functionality. In the remainder of this article we'll look at how to build a custom Web control (nicely named RequiredFieldValidatorForCheckBoxLists) that will encapsulate the desired functionality. While this may sound like quite a chore, it is really quite simple since new custom controls can extend the functionality of existing controls. Hence, our new RequiredFieldValidatorForCheckBoxLists Web control will extend the System.Web.UI.WebControls.BaseValidator class; all we have to do is simply override two methods of the BaseValidator class!

If you have Visual Studio .NET, you will find this task a whole lot easier than if you don't have it, but VS.NET is not required by any means. If you have VS.NET, create a new C# ASP.NET Web Control project; if you lack VS.NET, create a file with a .cs extension. Now, into your new file, insert the following code:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace CustomValidators
  public class RequiredFieldValidatorForCheckBoxLists : 
     private ListControl _listctrl;
     public RequiredFieldValidatorForCheckBoxLists()
       base.EnableClientScript = false;
     protected override bool ControlPropertiesValid()
       Control ctrl = FindControl(ControlToValidate);
       if (ctrl != null) 
         _listctrl = (ListControl) ctrl;
         return (_listctrl != null);   
         return false;  // raise exception
     protected override bool EvaluateIsValid()
       return _listctrl.SelectedIndex != -1;

First off, notice how concise the code is. This is because we are inheriting a large portion of the functionality needed in our RequiredFieldValidatorForCheckBoxLists control from the BaseValidator class. (The : System.Web.UI.WebControls.BaseValidator syntax after the public class RequiredFieldValidatorForCheckBoxLists indicates the the RequiredFieldValidatorForCheckBoxLists class inherits the BaseValidator class.)

All we need to do is override the ControlPropertiesValid() and EvaluateIsValid() methods of BaseValidator. The ControlPropertiesValid() method returns a boolean indicating if the control set by the ControlToValidate property is valid. In this method we simply grab the control (using FindControl) and assign it to our member variable, _listctrl, which is a ListControl object. If the ControlToValidate property is not set or is set to a nonexistent server control, the property will return false. You may wish to raise an exception at this point, for just returning false will cause the page to render like normal, just without the validation control. If the control is found, the control is cast to a ListControl and assigned to _listctrl. (You may wish to place this in a try ... catch block - as is, if you specify ControlToValidate to something other than a ListControl you'll get an illegal cast exception.)

The EvaluateIsValid() method returns a boolean that indicates whether or not the value in the control to be validated is valid or not. Since we are interested that at least one item has been selected, we simply return if the _listctrl ListItem control has had an item selected (if it has, SelectedIndex will be greater than -1). That's all there is to it!

Note that the code contains one other addition - the RequiredFieldValidatorForCheckBoxLists() constructor, which sets base.EnableClientScript to false. This has the effect of turning off the client-side behaviors of the validation controls. I needed to do this to get everything working properly. (If you can figure out a way to have ASP.NET's client-side library integrate with this custom validation control, please let me know!)

Compiling the Custom Control
If you have Visual Studio .NET, this task is a breeze - simply choose Build/Build Solution, and the DLL will be created. If you do not have VS.NET you will need to drop to the command line and navigate to the directory that contains the .cs file with the source code presented above. Once there, enter the following command:

csc /t:library /r:System.Web.dll filename.cs

This will create a DLL file named filename.dll in the same directory as the source file.

Using the Custom Web Control
Now that you have the DLL, to use the Web control you need to copy it to the Web application's /bin directory (if you're using VS.NET you can simply add it as a Reference and VS.NET will automatically copy it to the /bin directory for you). You'll also need to add a Register directive to the top of your ASP.NET Web pages that use the control (see the following example for the syntax). The below ASP.NET Web page shows a simple example of using this custom control to validate a CheckBoxList - a task that was impossible using the built-in RequiredFieldValidator.

<%@ Register TagPrefix="CustomValidators" Namespace="CustomValidators" 
                        Assembly="filename_of_DLL_file" %>
    <form runat="server">
      <asp:CheckBoxList id="CBList" runat="server">
        <asp:ListItem Value="Hello" />
        <asp:ListItem Value="World!" />

              id="reqCBList" runat="server" ControlToValidate="CBList" 
              ErrorMessage="Please select at least one checkbox..." />
      <asp:Button id="Button1"  runat="server" Text="Button" />      
[View a live demo!]

In this tip we looked at how to create a very simple required field validator validation Web control that could handle CheckBoxLists. Essentially, we only needed to override a couple of the methods from the BaseValidator class. Of course, our implementation is a bit weak - it's client-side support is nil and no code has been added to assist in displaying the Web control in toolbox in VS.NET. Regardless, we have a useful, compiled control that took only a small handful of lines of code. (Note that this custom control can also perform validation for other ListBox controls: DropDownLists, ListBox, RadioButtonList, etc. Of course for these you may just wish to use the standard RequiredFieldValidator...)

Happy Programming!
Return to user tips...

ASP.NET [1.x] [2.0] | ASPFAQs.com | Advertise | Feedback | Author an Article