Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 603
Amin AmiriDarban Avatar asked Sep 20 '13 19:09

Amin AmiriDarban


People also ask

How do I make Checkboxlist checked by default in asp net?

Answers. Just make Enabled = false.


2 Answers

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(); 
like image 181
Tim Schmelter Avatar answered Sep 16 '22 23:09

Tim Schmelter


foreach (ListItem item in CBLGold.Items) {     if (item.Selected)     {         string selectedValue = item.Value;     } } 
like image 36
Arif Ansari Avatar answered Sep 16 '22 23:09

Arif Ansari