Showing posts with label Type Extensions. Show all posts
Showing posts with label Type Extensions. Show all posts

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.

Wednesday, 29 May 2013

JavaScript - String Extensions #2 [ replaceAll() ]

Unfortunately function replace() in JavaScript replaces only the first matching SubString.
Here is an extension of String Type, which allows you to replace all the found SubStrings.
You can optionally specify more than one (array of strings) string to search for.
/****************************************
* String extensions
****************************************/
String.prototype.replaceAll = function (search, replace) {
    /// 
    /// Replaces all instances of [search] String or Array of Strings
    /// 

    var searches = [];
    if (Object.prototype.toString.call(search) === '[object Array]') {
        searches = search;
    } else {
        searches = [search];
    }
    var result = this + "";
    for (var i = 0; i < searches.length; i++) {
        result = result.split(searches[i]).join(replace);
    }

    return result;
};

Usage of simple replace:
var someString = "aaa-bbb-ccc-ddd";
var resultCsv = someString.replaceAll("-", ";");

Replace array of strings:
var someString = "aaa-bbb#ccc:ddd";
var resultCsv = someString.replaceAll(["-", "#", ":"], ";");