- Posted by ian suttle on May 14, 2008
- Filed under .NET 3.5 | .Net Framework | ASP.Net | C# 3.0
If you're like me you've often pondered why controls like CheckBoxList don't provide a way to get a collection of selected items. You've always had the option to iterate the Items collection and evaluate the Selected property, but why should that have to be done over and over again? I want a quick way to get the selected items from a CheckBoxList, ListBox, DropDownList, and RadioButtonList; all items which inherit from ListControl.
The excellent creation of extension methods makes it simple to get the selected items from a ListControl.
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace ListControlExtensions
{
public static class ListExtensions
{
public static List<ListItem> SelectedItems(this ListControl list)
{
List<ListItem> items = new List<ListItem>();
foreach (ListItem item in list.Items)
{
if (item.Selected)
{
items.Add(item);
}
}
return items;
}
}
}
Have you found an alternative to getting the selected items from a ListControl without looping through the Items collection?
.aspx&bgcolor=0099FF&cfgcolor=FFFFFF&cbgcolor=3300CC)