Check if at least one checkboxlist is selected

user1858332 picture user1858332 · Mar 6, 2013 · Viewed 29.2k times · Source

I have checkboxlist and I would like to check if at least one checkbox is checked. If none is checked then I want to show alert message that says please select at least one item. I want to do this in code behind if possible. I have started but don't know if it is right or wrong but not able to finish it.

 public void alert()
    {
        foreach (ListItem listItem in cblCustomerList.Items)
        {
            if (!listItem.Selected)
            {
            }
        }
    }

here is the checkboxlist in aspx:

 <asp:CheckBoxList ID="cblCustomerList" runat="server" DataSourceID="SqlDataSource1" CssClass="CheckBoxList"
            DataTextField="GroupName" DataValueField="GroupName" 
                onclick="readCheckBoxList()" >               
            </asp:CheckBoxList>

here is the button:

 <asp:Button ID="Button1" runat="server" CausesValidation="True" 
                            CommandName="Insert" Text="Insert" OnClientClick="return Validate_Checkbox()" />

Thanks for your help.

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Mar 6, 2013
if(cblCustomerList.Items.Cast<ListItem>().Any(item => item.Selected))
{
   // at least one selected
}