ListControl SelectedItem Validator





3.00/5 (20 votes)
Mar 24, 2002
1 min read

145281

37
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);
}
}
}