Extended CheckBoxList Control

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);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: