How To Validate Checkboxlist control in ASP.NET

<%@ 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;
       }

   }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru