Monday, 17 June 2013

.NET - Extend ListControl with GetSelectedItems and GetSelectedValues

Sometimes we need to get from ListBox or CheckBoxList the all selected items. Unfortunately there is only one ready to use function: GetSelectedIndices().
With the help of a very simple extensions we can add two additional functions, GetSelectedItems() and GetSelectedValues():
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

namespace TypeExtensions
{
    // ReSharper disable InconsistentNaming
    public static class System_Web_UI_ListControl
    // ReSharper restore InconsistentNaming
    {
        /// <summary>
        /// Returns ListControl selected items.
        /// </summary>
        public static List<ListItem> GetSelectedItems(this ListControl listControl)
        {
            var selectedItems = listControl.Items
                .OfType<ListItem>()
                .Where(listItem => listItem.Selected)
                .ToList();
            return selectedItems;
        }

        /// <summary>
        /// Returns ListControl selected values.
        /// </summary>
        public static List<string> GetSelectedValues(this ListControl listControl)
        {
            var selectedItems = listControl.GetSelectedItems();
            var selectedValues = selectedItems
                .Select(listItem => listItem.Value)
                .ToList();
            return selectedValues;
        }
    }
}

Simply add Namespace of this class to your namespace usages and you will become two additional functions:


These extension functions are working for all ListControl-based classes.