A common task in programming is to retrieve all of the selected items or values from a CheckBoxList control. It is unfortunate that no native properties provide this already. However, extending the CheckBoxList to provide these is simple enough.
The extension I created provides four new properties:
- SelectedValuesString – A comma-delimited string of the selected values.
- SelectedValuesAsIntegers – An Integer List of the selected values.
- SelectedValuesAsStrings – A string List of the selected values.
- SelectedItemTextAsStrings – A string list of the text for the selected items.
public class ExtendedCheckBoxList : CheckBoxList { public string SelectedValuesString { get { return String.Join(",",SelectedValuesAsStrings); } } public IEnumerable SelectedValuesAsIntegers { get { int temp; return this.Items.Cast<ListItem>() .Where(i => i.Selected && int.TryParse(i.Value,out temp)).Select(i => int.Parse(i.Value)); } } public IEnumerable SelectedValuesAsStrings { get { return this.Items.Cast<ListItem>().Where(i => i.Selected).Select(i=>i.Value); } } public IEnumerable SelectedItemTextAsStrings { get { return this.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Text); } } }