How to select/check all items in a CheckBoxList in asp.net

asp.net checkboxlist select/check all
The following asp.net c# example code demonstrate us how can we select or checked all items programmatically at run time in a CheckBoxList server control.

CheckBoxList control's each item represent a ListItem object. ListItem object's 'Selected' property allow web developers to select the specified item. We can set this Selected property value both declarative way in inline code and programmatically in c# script section. Selected property accept a Boolean value. 'True' value indicate the specified item is selected.

To select CheckBoxList all items programmatically, first we need to loop through the items collection. In this example code, we perform a foreach loop to iterate through CheckBoxList all items. Next, we set each ListItem object's Selected property value to True while iterating through the items collection. Finally, CheckBoxList display all items are selected/checked.
checkboxlist-select-check-all.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>    
      
<!DOCTYPE html>
        
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    { 
        if(!Page.IsPostBack)
        {
            string[] birds = { 
                                 "Green Magpie",
                                 "Red-billed Chough",
                                 "Piapiac",
                                 "Western Jackdaw",
                                 "House Crow"
                             };

            CheckBoxList1.DataSource = birds;
            CheckBoxList1.DataBind();
        }
    }
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        foreach(ListItem li in CheckBoxList1.Items)
        {
            li.Selected=true;
        }
    }
</script>        
        
<html xmlns="http://www.w3.org/1999/xhtml">        
<head id="Head1" runat="server">        
    <title>asp.net checkboxlist select/check all</title>
</head>        
<body>        
    <form id="form1" runat="server">        
    <div>        
        <h2 style="color:MidnightBlue; font-style:italic;">        
            asp.net example - checkboxlist select/check all
        </h2>        
        <hr width="550" align="left" color="Gainsboro" />        
        <br /><br />
        <asp:CheckBoxList 
            ID="CheckBoxList1"
            runat="server"
            RepeatColumns="2"
            >
        </asp:CheckBoxList>  
        <br /> 
        <asp:Button   
            ID="Button1"   
            runat="server"   
            Text="check all items"  
            OnClick="Button1_Click"
            Height="40"  
            Font-Bold="true"  
            />  
    </div>        
    </form>        
</body>        
</html>
More asp.net examples