Question

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
    {

    }
}
Was it helpful?

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

OTHER TIPS

Are you sure you mean override? Or do you really mean "override and overload as appropriate?"

I'd overload the Add method to include an overload that takes a CSV string, parse it into an array of strings (or List) and pass it to AddRange.

I'd also override ToString() to return the values as a CSV list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top