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():
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Web.UI.WebControls;
  4.  
  5. namespace TypeExtensions
  6. {
  7. // ReSharper disable InconsistentNaming
  8. public static class System_Web_UI_ListControl
  9. // ReSharper restore InconsistentNaming
  10. {
  11. /// <summary>
  12. /// Returns ListControl selected items.
  13. /// </summary>
  14. public static List<ListItem> GetSelectedItems(this ListControl listControl)
  15. {
  16. var selectedItems = listControl.Items
  17. .OfType<ListItem>()
  18. .Where(listItem => listItem.Selected)
  19. .ToList();
  20. return selectedItems;
  21. }
  22.  
  23. /// <summary>
  24. /// Returns ListControl selected values.
  25. /// </summary>
  26. public static List<string> GetSelectedValues(this ListControl listControl)
  27. {
  28. var selectedItems = listControl.GetSelectedItems();
  29. var selectedValues = selectedItems
  30. .Select(listItem => listItem.Value)
  31. .ToList();
  32. return selectedValues;
  33. }
  34. }
  35. }

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.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.