Search code examples
c#asp.netlistboxlistbox-control

Override the Listbox Control to return a concatenated string value


I have to redefine the ListBox class to make sure that it returns a csv string of all the selected items and also should take in a csv string and populate the listbox when needed. Lets say I have this code. What are the functions that I have to override and how do I do it?

using System;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace MY.WebControl
{
    public class ListBoxString : ListBox
    {

    }
}

Solution

  • If all you want to do is add functionality, you can also add Extension Methods to add this capability. Here are 2 quick examples that GetSelectItems to a CSV string and AddListItems from a string array.

        public static string GetSelectedItems(this ListBox lbox)
        {
            List<string> selectedValues = new List<string>();
    
            int[] selectedIndeces = lbox.GetSelectedIndices();
    
            foreach (int i in selectedIndeces)
                selectedValues.Add(lbox.Items[i].Value);
    
            return String.Join(",",selectedValues.ToArray());
        }
    
        public static void SetSelectedItems(this ListBox lbox, string[] values)
        {
            foreach (string value in values)
            {
                lbox.Items[lbox.Items.IndexOf(lbox.Items.FindByValue(value))].Selected = true;
            }
        }
    
        public static void AddListItems(this ListBox lbox, string[] values)
        {
            foreach (string value in values)
            {
                ListItem item = new ListItem(value);
                lbox.Items.Add(item);
            }
        }