How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

Amin AmiriDarban picture Amin AmiriDarban · Sep 20, 2013 · Viewed 308.3k times · Source

I have a CheckBoxList like this:

<asp:CheckBoxList ID="CBLGold" runat="server" CssClass="cbl">
    <asp:ListItem Value="TGJU"> TG </asp:ListItem>
    <asp:ListItem Value="GOLDOZ"> Gold </asp:ListItem>
    <asp:ListItem Value="SILVEROZ"> Silver </asp:ListItem>
    <asp:ListItem Value="NERKH"> NE </asp:ListItem>
    <asp:ListItem Value="TALA"> Tala </asp:ListItem>
    <asp:ListItem Value="YARAN"> Sekeh </asp:ListItem>
</asp:CheckBoxList>

Now I want to get the value of the selected items from this CheckBoxList using foreach, and put the values into a list.

Answer

Tim Schmelter picture Tim Schmelter · Sep 20, 2013

Note that I prefer the code to be short.

List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .ToList();

or with a simple foreach:

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
    if (item.Selected) selected.Add(item);

If you just want the ListItem.Value:

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .ToList();