Click here to Skip to main content
Licence 
First Posted 23 Mar 2002
Views 125,866
Bookmarked 30 times

ListControl SelectedItem Validator

By | 23 Mar 2002 | Article
RequiredField Validator for ASP.NET ListControl derived webserver controls

Introduction

As you all know the ASP.NET RequiredFieldValidator control checks that the validated control to see if it contains a value. If it doesn't it displays an error message. The problem is that RequiredFieldValidator does not work for ListControl derived controls (except ListBox) such as

  • DropdownList
  • CheckBoxList
  • RadioButtonList

And actually it throws an exception in the CheckControlValidationProperty(String name,String propertyName) function if you try to set the ControlToValidate property of the RequiredFieldValidator control to one of the above controls. So I decided to write a server side validation control to do this.

Basically I have derived from BaseValidator which provides the base implementation for all validation controls. It is not an abstract class. I have overridden only two functions which are

  • ControlPropertiesValid()
  • EvaluateIsValid()

The first one checks the validity of the ControlToValidate property and if you return false in this function , the validation framework raises an exception. EvaluateIsValid is the main function which checks if there is a selected item in the ListControl. If the function doesn't return false then this means validation fails. 

An interesting Point is since the DropDownList control can not have a SelectedIndex property with a value of –1 , I checked against 0 so you may want to insert an empty item in the beginning.

So enough with the talk lets take a look at the code.

//
// 
//
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace MyValidations
{
    [DefaultProperty("ErrorMessage")]
    public class RequiredSelectedItemValidator : System.Web.UI.BaseValidator 
    {
        private ListControl _listctrl;
 
        protected override bool ControlPropertiesValid()
        {
           Control ctrl = FindControl(ControlToValidate);
       
           If (ctrl != null)
           {
               _listctrl = ctrl as ListControl;
               return (_listctrl != null);     
           }
           else 
              return false;  // raise exception
       }
 
       protected override bool EvaluateIsValid()
       {      
            return (_listctrl is DropDownList) ? (_lisctrl.SelectedIndex != 0) : 
                                                 ( _lisctrl.SelectedIndex != -1);
       }
   }
}

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

Cenk Civici



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHeard of Attributes? PinmemberRob van der Veer23:12 23 Sep '05  
GeneralThis is unnecessary for DropDownList WebControls PinmemberGerald Bryant6:48 19 May '05  
Set the InitialValue property to a non-emptry string such as "0", "~", something NOT in your valid list. When a postback is attempted the RequiredFieldValidator assigned to the DropDownList will test the Selected.Value against it's InitialValue. If you list is coming from a Stored Procedure, use a union query to return an initial value/text item and then the data itself (ie. SELECT '~', 'None' UNION Select keyID, fldState FROM tblStates) making sure the non-choice's value can sort first in the list.
For instance when creating a list of payment methods and an initial non-choice in the form Value, Text
~,(Please choose a payment method)
0,Maxed-Out MasterCard
1,Stolen Visa
2,Discovered in someone's trash Discover
3,Hijacked PayPal Account
4,Counterfiet Money Order
5,Bounced Check
6,Laser-printed Cash
 
G. Bryant
GeneralYet another solution PinmemberLordJM0:54 6 Apr '05  
GeneralRe: Yet another solution PinmemberMyster17:10 11 Apr '05  
Generalfixes required to make this work Pinmembermagister8:08 22 Feb '05  
GeneralIt is Server Side PinmemberGeorge Mamaladze22:48 2 Sep '04  
GeneralThis works PinmemberMichael Yourshaw17:24 25 Jun '03  
GeneralHas anybody got this to work PinmemberJefferys5:54 10 Mar '03  
GeneralRe: Has anybody got this to work PinsussAnonymous6:45 10 Mar '03  
GeneralRe: Has anybody got this to work PinmemberJefferys6:52 10 Mar '03  
GeneralRe: Has anybody got this to work PinmemberMyster19:29 12 Apr '05  
GeneralAnother solution... PinmemberCypher10:09 11 Feb '03  
GeneralRe: Another solution... PinmemberphishBone18:21 20 Aug '03  
GeneralRe: Another solution... PinsussAnonymous11:19 29 Jan '04  
GeneralRe: Another solution... Pinmembercosmoansaldi8:44 30 Jun '05  
General3.5 from 2 votes... PinmemberNish [BusterBoy]8:31 25 Mar '02  
GeneralRe: 3.5 from 2 votes... Pinmemberccivici17:13 25 Mar '02  
GeneralRe: 3.5 from 2 votes... PinmemberNish [BusterBoy]17:27 25 Mar '02  
GeneralRe: 3.5 from 2 votes... Pinmemberccivici17:23 25 Mar '02  

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120528.1 | Last Updated 24 Mar 2002
Article Copyright 2002 by Cenk Civici
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid