Tuesday, April 19, 2011

Sort a Listbox using IComparer in C#

What are we cooking today?
Sort a Listbox using IComparer in C# without loosing the value. 

RECIPE

The call
 SortList(MyListbox);

The Procedure

public void SortList(ListBox list)
{
        try
        {
            //---FROM LISTBOX TO LIST<>
            List ListItems = new List();
            foreach (ListItem lst in list.Items)
            {
                ListItems.Add(lst);
            }

            //---SORT LIST<>
            ListItemComparer listC = new ListItemComparer();
            ListItems.Sort(listC.Compare);

            //---CLEAR LISTBOX
            list.Items.Clear();

            //---ADD FROM ordered LIST<> to LISTBOX
            foreach (ListItem li in ListItems)
            {
                list.Items.Add(li);
            }
        }

        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
           
        }//--end catch
    }

The Icomparer: I am using this because a listitem has text and value, and we just want to order by the text, which could be a person's name or a product( the criteria could be also the value like price, personId, year...)


public class ListItemComparer : IComparer
{
    public int Compare(ListItem a, ListItem b)
    {
        int result = string.Compare(a.Text, b.Text);
        return result;
    }
}

No comments:

Post a Comment