![]() |
Web Development »
Validation »
General
Intermediate
ListControl SelectedItem ValidatorBy Cenk CiviciRequiredField Validator for ASP.NET ListControl derived webserver controls |
C#, Windows, .NET 1.0, ASP.NET, Visual Studio, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
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
DropdownListCheckBoxListRadioButtonListAnd
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);
}
}
}
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 23 Mar 2002 Editor: Chris Maunder |
Copyright 2002 by Cenk Civici Everything else Copyright © CodeProject, 1999-2009 Web18 | Advertise on the Code Project |