How to set the maximum limit of selection in a CheckBoxList checkboxlist limit selection
CheckBoxList is an web server control which render a multi selection check box group on web page. by default, users can select as many items as they want from a checkboxlist. but sometimes .net developers need to limit checkboxlist items selection.

In this example, we limit the checkboxlist items selection to 3. that mean users can select up to 3 items from checkboxlist. to do this, we need to apply few steps. first we write an event handler for checkboxlist SelectedIndexChanged event. then we apply a linq query to populate an items collection from only checkboxlist selected items.

Next we count the selected items collection's items. if the selected items are greater than 3 then we deselect the last selected item and display a message to user that you can select up to 3 items. finally it makes the checkboxlist selection limit to 3. checkboxlist items.Last().Selected provide us a way to get the checkboxlist last selected item.

The following c# example code demonstrate us how can we apply limit selection for a checkboxlist in an application.

<%@ Page Language="C#" AutoEventWireup="true"%>    
<!DOCTYPE html>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
            CheckBoxList1.Items.Add(new ListItem("Spotted Nutcracker", "1"));
            CheckBoxList1.Items.Add(new ListItem("Alpine Chough", "2"));
            CheckBoxList1.Items.Add(new ListItem("Green Magpie", "3"));
            CheckBoxList1.Items.Add(new ListItem("Eurasian Jay", "4"));
            CheckBoxList1.Items.Add(new ListItem("Carrion Crow", "5"));

    protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
        // linq query to find selected items from checkboxlist
        var items = from ListItem li in CheckBoxList1.Items
                    where li.Selected == true
                    select li;

        Label1.Text = "";
        if(items.Count() > 3)
            Label1.Text = "<b>checked maximum 3 items.</b><br />";
            items.Last().Selected = false;
        Label1.Text += "you checked item(s).....<br />";

        foreach (ListItem li in items)
            Label1.Text += li.Text+" | "+li.Value +"<br />";
<html xmlns="">        
<head id="Head1" runat="server">        
    <title> checkboxlist limit selection</title>
    <form id="form1" runat="server">        
        <h2 style="color:MidnightBlue; font-style:italic;">        
   example - checkboxlist limit selection
        <hr width="550" align="left" color="Gainsboro" />        
            Text="check maximum 3 items from checkboxlist."
        <br /><br />
More examples