In this article I will explain with an example, how to check uncheck all (select unselect all) CheckBoxes in ASP.Net CheckBoxList using C# and VB.Net.
The check uncheck all functionality will be done using an additional CheckBox that will act as Check All CheckBox for the ASP.Net CheckBoxList control.
HTML Markup
The HTML Markup consists of an ASP.Net CheckBox for check uncheck all (select unselect all) functionality and an ASP.Net CheckBoxList control.
The CheckBox has been assigned OnCheckChanged event handler and the AutoPostBack property is set to True.
The CheckBoxList control has been assigned OnSelectedIndexChanged event handler and the AutoPostBack property is set to True.
<asp:CheckBox ID="chkAll" Text="Select All" runat="server" OnCheckedChanged = "Check_UnCheckAll" AutoPostBack = "true" />
<asp:CheckBoxList ID="chkFruits" runat="server" OnSelectedIndexChanged = "CheckBox_Checked_Unchecked" AutoPostBack = "true">
<asp:ListItem Text="Mango" />
<asp:ListItem Text="Apple" />
<asp:ListItem Text="Banana" />
<asp:ListItem Text="Pineapple" />
<asp:ListItem Text="Guava" />
<asp:ListItem Text="Grapes" />
<asp:ListItem Text="Papaya" />
</asp:CheckBoxList>
Check Uncheck all CheckBoxes when Check All CheckBox is checked
When the Check All CheckBox is checked or unchecked, the following event handler is executed.
A loop is executed over all the CheckBoxes of the CheckBoxList control and each CheckBox is checked or unchecked based on whether the Check All CheckBox is checked or unchecked.
C#
protected void Check_UnCheckAll(object sender, EventArgs e)
{
foreach (ListItem item in chkFruits.Items)
{
item.Selected = chkAll.Checked;
}
}
VB.Net
Protected Sub Check_UnCheckAll(ByVal sender As Object, ByVal e As EventArgs)
For Each item As ListItem In chkFruits.Items
item.Selected = chkAll.Checked
Next
End Sub
Check Uncheck Check All CheckBox when other CheckBoxes are checked or unchecked
When any CheckBox of the CheckBoxList control is checked or unchecked, the following event handler is executed.
A loop is executed over all the CheckBoxes of the CheckBoxList control and based on whether all the CheckBoxes of the CheckBoxList control are checked or unchecked, the Check All CheckBox is checked or unchecked.
C#
protected void CheckBox_Checked_Unchecked(object sender, EventArgs e)
{
bool isAllChecked = true;
foreach (ListItem item in chkFruits.Items)
{
if (!item.Selected)
{
isAllChecked = false;
break;
}
}
chkAll.Checked = isAllChecked;
}
VB.Net
Protected Sub CheckBox_Checked_Unchecked(ByVal sender As Object, ByVal e As EventArgs)
Dim isAllChecked As Boolean = True
For Each item As ListItem In chkFruits.Items
If Not item.Selected Then
isAllChecked = False
Exit For
End If
Next
chkAll.Checked = isAllChecked
End Sub
Screenshot
Demo
Downloads