Saturday, June 14, 2014

Select or Deselect All list items in CheckBoxlist

Example :-
WebForm1.aspx :-
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="_24_Select_Deselect.WebForm1" %>  
 <!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 runat="server">  
   <title></title>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div>  
     <asp:Button ID="Button2" runat="server" onclick="Button2_Click1"   
       Text="Select All" />  
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
     <asp:Button ID="Button3" runat="server" onclick="Button3_Click"   
       Text="Deselect All" />  
     <br />  
     <asp:CheckBoxList ID="CheckBoxList1" runat="server">  
       <asp:ListItem Value="1">Diploma</asp:ListItem>  
       <asp:ListItem Value="2">Graduate</asp:ListItem>  
       <asp:ListItem Value="3">Post Graduate</asp:ListItem>  
       <asp:ListItem Value="4">Doctrate</asp:ListItem>  
     </asp:CheckBoxList>  
     <br />  
     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />  
     <br />  
   </div>  
   </form>  
 </body>  
 </html>  

WebForm1.aspx.cs :-
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 namespace _24_Select_Deselect  
 {  
   public partial class WebForm1 : System.Web.UI.Page  
   {  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       if (!IsPostBack)  
       {  
         CheckBoxList1.SelectedValue = "2"; //When the page is loaded Graduate will be selected using list item value  
         //CheckBoxList1.SelectedIndex = 0;  //When the page is loaded Diploma will be selected using list item index  
       }  
     }  
     protected void Button1_Click(object sender, EventArgs e)  
     {  
       foreach (ListItem li in CheckBoxList1.Items)  
       {  
         if (li.Selected)  
         {  
           Response.Write(li.Text + ", ");  
         }  
       }  
     }  
     protected void Button2_Click1(object sender, EventArgs e)  
     {  
       foreach (ListItem li in CheckBoxList1.Items)  
       {  
         li.Selected = true;  
       }  
     }  
     protected void Button3_Click(object sender, EventArgs e)  
     {  
       foreach (ListItem li in CheckBoxList1.Items)  
       {  
         li.Selected = false;  
       }  
     }  
   }  
 }  

No comments:

Post a Comment