How To Validate Checkboxlist control

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidateCheckBoxList.aspx.cs"
   Inherits="ValidateCheckBoxList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="">
<head id="Head1" runat="server">
   <title>Untitled Page</title>
   <form id="form1" runat="server">
           <asp:CheckBoxList ID="CheckBoxList1" runat="server">
               <asp:ListItem Text="a" Value="b"></asp:ListItem>
               <asp:ListItem Text="a" Value="b"></asp:ListItem>
           <asp:CustomValidator ID="CustomValidator1" runat="server"
           <asp:Button ID="Button1" runat="server" Text="Validate" /></div>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ValidateCheckBoxList : System.Web.UI.Page
   protected void Page_Load(object sender, EventArgs e)

   protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
       int i;
       i = 0;

       foreach (ListItem item in CheckBoxList1.Items)
           if (item.Selected)
               i = i + 1;

       if (i > 1)
           args.IsValid = false;
           CustomValidator1.ErrorMessage = "more than one item is selected!";
           args.IsValid = true;


1 comment:

  1. Hi,

    This is very informative article. Thanks for sharing your knowledge. There are few links that also helpful for developers. This article have described to validate CheckBox, CheckBoxList, DropDownList, FileUpload, RadioButton, RadioButtonList, TextBox using jquery.