How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?
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();
foreach (ListItem item in CBLGold.Items)
{
if (item.Selected)
{
string selectedValue = item.Value;
}
}
Good afternoon, you could always use a little LINQ to get the selected list items and then do what you want with the results:
var selected = CBLGold.Items.Cast<ListItem>().Where(x => x.Selected);
// work with selected...
Following suit from the suggestions here, I added an extension method to return a list of the selected items using LINQ for any type that Inherits from System.Web.UI.WebControls.ListControl
.
Every ListControl
object has an Items
property of type ListItemCollection
. ListItemCollection
exposes a collection of ListItems
, each of which have a Selected
property.
C Sharp:
public static IEnumerable<ListItem> GetSelectedItems(this ListControl checkBoxList)
{
return from ListItem li in checkBoxList.Items where li.Selected select li;
}
Visual Basic:
<Extension()> _
Public Function GetSelectedItems(ByVal checkBoxList As ListControl) As IEnumerable(Of ListItem)
Return From li As ListItem In checkBoxList.Items Where li.Selected
End Function
Then, just use like this in either language:
myCheckBoxList.GetSelectedItems()