Skip to main content

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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:CheckBoxList ID="CheckBoxList1" runat="server">
               <asp:ListItem Text="a" Value="b"></asp:ListItem>
               <asp:ListItem Text="a" Value="b"></asp:ListItem>
           </asp:CheckBoxList>
           <asp:CustomValidator ID="CustomValidator1" runat="server"
 ErrorMessage="CustomValidator"
               OnServerValidate="CustomValidator1_ServerValidate">
           </asp:CustomValidator>
           <asp:Button ID="Button1" runat="server" Text="Validate" /></div>
   </form>
</body>
</html>



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!";
       }
       else
       {
           args.IsValid = true;
       }

   }
}

Comments

  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.

    http://mindstick.com/Articles/c3825daa-a449-467d-9513-34a8232d498a/?Validations%20on%20Asp%20Net%20Control

    http://www.aspdotnet-suresh.com/2012/09/jquery-validate-checkboxlist-in-aspnet.html

    ReplyDelete

Post a Comment

Popular posts from this blog