Active Server Pages Programming (ASP)/checboxlist validation

Advertisement


Question
Hey,

I hav an application which uses a checkboxlist with 6 checkboxes. I would like to make sure at least one of the checkboxes is checked. I have tried many versions of validation but cannot get this to work. Can you shed any light on what to do?

Cheers

Paul

Answer
Hi,

You can use Custom validation to check CheckboxList

Here is the sample code.

  
   private void User_Choice(object sender, ServerValidateEventArgs e)
   {
       int counter = 0;
   
       for(int i=0;i<chkboxPeeps.Items.Count;i++)
       {
           if(chkboxPeeps.Items[i].Selected)
           {
               counter++;
           }
   
           e.IsValid = (counter == 0) ? false : true;
       }
   }
   
   public void ValidateForm(object sender, EventArgs e)
   {
       if(Page.IsValid)
       {
           //success
       }
       else
       {
           failed validation msg
       }
   }


<asp:CheckBoxList id="chkboxPeeps"  runat="server"/>
<asp:CustomValidator id="customvalidation" runat="server" display="dynamic" text="You need to select at least one of the choices to be valid" OnServerValidate="User_Choice"/>           
<asp:Button id="btnSubmit" Text="Check" OnClick="ValidateForm" runat="server"/>

Hope this helps!!

-Srini

Active Server Pages Programming (ASP)

All Answers


Answers by Expert:


Ask Experts

Volunteer


Srini Nagarajan

Expertise

I can answer any kind of questions in ASP.NET, C#, VB.NET, SharePoint 2007, ASP, Coldfusion, Powerbuilder 7.00 / 8.00, JAVA servlets, MS SQL 2000 / MSSQL7, Sybase

Experience

Contact me if you need any custom development on ASP.NET, ASP, SharePoint 2007, Coldfusion, Powerbuilder.

©2012 About.com, a part of The New York Times Company. All rights reserved.