SelectedCountValidator Control
Life With Nate
Nate's Poetry Page
Resume (PDF)
Nate's Code
ASP.NET 2.0/3.5
ButtonExtensions
ConditionalRequiredTextValidator
CSSImageMap
CustomStyle
DateTimePicker
DateTimePickerTemplated
LengthValidator
RestrictInputTextBox
RestrictInputValidator
Rollovers
RotatedTextHandler
RotatedTextImage
Rotators
SelectedCountValidator
SlideIntoView
StatesDropDownList
UniqueValueValidatorBase
VB.NET 2.0/3.5
Just For Fun
Windows Phone 7
Description
The SelectedCountValidator inherits from System.Web.UI.WebControls.BaseValidator and is used to validate how many CheckBoxes in a CheckBoxList or ListItems in a ListBox are selected.
Example
CheckBoxList1
CheckBoxList6
CheckBoxList2
CheckBoxList7
CheckBoxList3
CheckBoxList8
CheckBoxList4
CheckBoxList9
CheckBoxList5
CheckBoxList10
ListBox1
ListBox2
ListBox3
ListBox4
ListBox5
ListBox6
ListBox7
ListBox8
ListBox9
ListBox10
Properties & Methods
SelectedCountValidator
The SelectedCountValidator inherits from System.Web.UI.WebControls.BaseValidator and is used to validate how many CheckBoxes in a CheckBoxList or ListItems in a ListBox are selected.
ControlToValidate
- (Inherited from BaseValidator) The ID of the CheckBoxList or ListBox for which a minimum and/or maximum number of selected items will be specified
MinimumSelected
- The minimum number of items that must be checked or selected
MaximumSelected
- The maximum number of items that may be checked or selected
GenerateErrorMessage
- A Boolean value specifying whether the ErrorMessage property should be automatically generated (Default="True")
Source Code
SelectedCountValidator.vb:
Namespace NathanSokalski <System.Drawing.ToolboxBitmap(GetType(ToolboxIcons), "SelectedCountValidator.bmp")> _ Public Class SelectedCountValidator : Inherits System.Web.UI.WebControls.BaseValidator Private _minimumselected As Integer = 0, _maximumselected As Integer Private _generateerrormessage As Boolean = True Private minspecified As Boolean = False, maxspecified As Boolean = False <DefaultValue(0), _ Description("The minimum number of items that may be selected")> _ Public Property MinimumSelected() As Integer Get Return Me._minimumselected End Get Set(ByVal value As Integer) Me._minimumselected = value Me.minspecified = True End Set End Property <Description("The maximum number of items that may be selected")> Public Property MaximumSelected() As Integer Get Return Me._maximumselected End Get Set(ByVal value As Integer) Me._maximumselected = value Me.maxspecified = True End Set End Property <DefaultValue(True), _ Description("A Boolean value specifying whether a custom or generated error message should me used")> _ Public Property GenerateErrorMessage() As Boolean Get Return Me._generateerrormessage End Get Set(ByVal value As Boolean) Me._generateerrormessage = value End Set End Property Protected Overrides Function EvaluateIsValid() As Boolean Dim value As Byte = Me.SelectedCount() If Not Me.maxspecified Then Me._maximumselected = CType(Me.NamingContainer.FindControl(Me.ControlToValidate), ListControl).Items.Count Return value <= Me._maximumselected AndAlso value >= Me._minimumselected End Function Protected Overrides Function ControlPropertiesValid() As Boolean Dim acceptedtypes() As String = {"CheckBoxList", "ListBox"} Return acceptedtypes.Contains(TypeName(Me.NamingContainer.FindControl(Me.ControlToValidate))) End Function Protected Overrides Sub AddAttributesToRender(ByVal writer As System.Web.UI.HtmlTextWriter) MyBase.AddAttributesToRender(writer) writer.AddAttribute("evaluationfunction", "SelectedCountValidatorIsValid") If TypeName(Me.NamingContainer.FindControl(Me.ControlToValidate)) = "CheckBoxList" Then writer.AddAttribute("count", CType(Me.NamingContainer.FindControl(Me.ControlToValidate), CheckBoxList).Items.Count.ToString()) writer.AddAttribute("minimumselected", Me._minimumselected.ToString()) writer.AddAttribute("maximumselected", Me._maximumselected.ToString()) writer.AddAttribute("controltovalidatetype", TypeName(Me.NamingContainer.FindControl(Me.ControlToValidate))) End Sub Private Function SelectedCount() As Byte 'Determine the number of selected items in ControlToValidate Dim selcount As UShort = 0 Select Case TypeName(Me.NamingContainer.FindControl(Me.ControlToValidate)) Case "CheckBoxList" For Each item As ListItem In CType(Me.NamingContainer.FindControl(Me.ControlToValidate), CheckBoxList).Items If item.Selected Then selcount += 1US Next Case "ListBox" For Each item As ListItem In CType(Me.NamingContainer.FindControl(Me.ControlToValidate), ListBox).Items If item.Selected Then selcount += 1US Next End Select Return CByte(selcount) End Function Private Sub Ctrl_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender If Me._generateerrormessage Then If Me.maxspecified AndAlso Me.minspecified Then : Me.ErrorMessage = String.Format("You must select between {0} and {1} items.", Me._minimumselected, Me._maximumselected) ElseIf Me.maxspecified Then : Me.ErrorMessage = String.Format("You may not select more than {0} items.", Me._maximumselected) ElseIf Me.minspecified Then : Me.ErrorMessage = String.Format("You must select at least {0} items.", Me._minimumselected) End If End If Me.Page.ClientScript.RegisterClientScriptResource(Me.GetType(), "SelectedCountValidator.js") 'If the ControlToValidate is a CheckBoxList apply the validator to each individual generated CheckBox If TypeName(Me.NamingContainer.FindControl(Me.ControlToValidate)) = "CheckBoxList" Then Dim addcheckboxlistvalidators As New System.Text.StringBuilder() addcheckboxlistvalidators.AppendFormat("for(var i=0;i<{0};i++)", CType(Me.NamingContainer.FindControl(Me.ControlToValidate), CheckBoxList).Items.Count) addcheckboxlistvalidators.Append("{") addcheckboxlistvalidators.AppendFormat("ValidatorHookupControl(document.getElementById(""{0}""+""_""+i),document.getElementById(""{1}""));", Me.GetControlRenderID(Me.ControlToValidate), Me.ClientID) addcheckboxlistvalidators.Append("}") Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "AddCheckBoxListHandlers", addcheckboxlistvalidators.ToString(), True) End If End Sub End Class End Namespace
SelectedCountValidator.js:
function SelectedCountValidatorIsValid(val) { var selectedcount=0; switch(val.controltovalidatetype) { case "CheckBoxList": { for(var i=0;i<parseInt(val.count);i++){if(document.getElementById(val.controltovalidate+"_"+i).checked){selectedcount++;}} break; } case "ListBox": { for(var i=0;i<document.getElementById(val.controltovalidate).options.length;i++){if(document.getElementById(val.controltovalidate).options[i].selected==true){selectedcount++;}} break; } } return ((selectedcount<=parseInt(val.maximumselected))&&(selectedcount>=parseInt(val.minimumselected))); }
Remarks
Although the SelectedCountValidator will correctly validate a ListBox that has SelectionMode="Single", it is normally used only when SelectionMode="Multiple".