Getting Values of ASP.Net CheckBoxList Selected Items

Updated on 03 Jul 2012,
Published on 21 Oct 2009

The ASP.Net CheckBoxList control provides the functionality to select the multiple checkbox items. You can add the SelectedIndexChanged server side event to the CheckBoxList control to handle the click event raised by the user when he clicks the checkbox list item to select it. Attaching the SelectedIndexChanged event will execute the server side event handler each time the user will select the list item. You have to specify the value of AutoPostBack property of CheckBoxList control as "true" to enable the auto post back feature of the control so that it could submit the web page to the server and execute the server side event handler associated to it as we discussed in the previous tutorial: ASP.Net CheckBoxList OnSelectedIndexChanged Event. The CheckBoxList item does not have any property that could provide the collection of selected checkbox list items instead you have to checked the value of "Selected" property of each list item of the CheckBoxList control when the OnSelectedIndexChanged event occurs.

Sample Code to Get CheckBoxList Selected Items

HTML Code
<asp:CheckBoxList ID="CheckBoxList1" 
    runat="server" 
    AutoPostBack="True" 
    OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
    <asp:ListItem Value="Item 1">Item 1</asp:ListItem>
    <asp:ListItem Value="Item 2">Item 2</asp:ListItem>
    <asp:ListItem Value="Item 3">Item 3</asp:ListItem>
    <asp:ListItem Value="Item 4">Item 4</asp:ListItem>
    <asp:ListItem Value="Item 5">Item 5</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
C# Code
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.Text = string.Empty;

    foreach (ListItem listitem in CheckBoxList1.Items)
    {
        if (listitem.Selected)
            Label1.Text += listitem.Text + "<br />";
    }
}

In the above C# code we have used the "C# foreach loop" over the list items of CheckBoxList control. Inside the foreach loop we have placed "if condition" to check the value of "Selected" property of list item. After passing the "if condition" test the list item value will concatenate with the text value of Label control used to display the value of multiple selected items of checboxlist.

Output:

Get the output for above discussed code from the following link:

CheckBoxList Control Selected Items

Continue to next tutorial: Add Items to Populate ASP.Net CheckBoxList Control Dynamically to learn how to add list items using C# code programmatically.

0 Responses to "Getting Values of ASP.Net CheckBoxList Selected Items"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email