Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / C#
Article

Ordered ListBox

Rate me:
Please Sign up or sign in to vote.
4.98/5 (47 votes)
29 Jul 2002CPOL2 min read 166.2K   1.6K   33   14
A ListBox derived class that supports internal ordering and re-ordering of items

Overview

The OrdListBox is a class derived from System.Windows.Forms.ListBox and was written by me when I was working on a project where I had this requirement of having ordered items in a list box. The issue was that there might be multiple copies of the same item in the list box and I had no way to differentiate among these duplicate items. The duplicate items would obviously be textual abstractions of distinct underlying objects. MFC had

CListBox::SetItemData
which allowed us to associate a 32 bit value with an item in the list box. I assumed rather enthusiastically that there would be something analogous to that in the .NET ListBox class. It was with an intense annoyance that I realized that I couldn't find anything to do the job. Of course for all I know there might be some hidden feature somewhere which I had overlooked and missed. But anyway I had to write my own class to achieve what I wanted to. I was a little stuck when Shog9 brilliantly helped me out with a beautiful but simple suggestion that I totally missed out on.

Purpose

The class basically allows you to associate strings with each list box item. Now when you add an item to the string using the new method added to the derived class, this order string will be used to determine the position where this new item would be inserted at. The order string can be either numeric or non-numeric. If the order string is numeric then 6 comes before 12, but if the order string is non-numeric you must watch out, because 6 is now greater than 12 on account of it's position in the character set.

Sample Usage

C#
//...

/* Create a new OrdListBox with numeric order */
OrdListBox listBox1 = new OrdListBox(true);

//...

/* You must use this method to add items to the 
 list box. Because if you use ListBox methods
 to add items, the class will obviously fail!  */
listBox1.AddOrderedItem(textBox1.Text,textBox2.Text);

//...

/* You can call ListBox methods too */
listBox1.Items.RemoveAt(listBox1.SelectedIndex);

//...

/* GetItemOrder can be used to return the order */
MessageBox.Show(
    listBox1.GetItemOrder(listBox1.SelectedIndex),
    listBox1.Items[listBox1.SelectedIndex].ToString());

//...

Function Reference

Constructor

Initializes a new instance of the OrdListBox class.

public OrdListBox( bool bNum );

  • bNum - Set this to true to make the ordering numeric and to false to make the ordering non-numeric.

AddOrderedItem

This will add a new ordered item to the ordered  list box, and it will insert the new item at the correct position within the list box, that will maintain the order of the items in the list box, after the new item has been added to it.

public void AddOrderedItem(string ItemText, string ItemOrder);

  • ItemText - This is the text of the item to be added to the ordered list box.
  • ItemOrder - This is the order string that will specify the order value of the item to be added.

GetItemOrder

This method will return the order value of an item in a list box given the index of the item within the list box.

public string GetItemOrder(int index)

  • index - This is the index of the required item within the list box.

Return Value

The method will return a string that represents the order value of the specified list box item.

Code Listing

C#
public class OrdListBox : System.Windows.Forms.ListBox
{

    public OrdListBox(bool bNum)
    {
        bNumeric = bNum;
        Sorted = false; //required
    }

    public void AddOrderedItem(string ItemText, string ItemOrder)
    {
        ItemData data = new ItemData(ItemText,ItemOrder);
        int c = Items.Count;    

        /* Loop through list box and locate 
         point of insertion */
        for (int i = 0; i < Items.Count; i++)
        {
            if (data.IsLess((ItemData)Items[i],bNumeric))
            {
                //Found! Now insert
                Items.Insert(i,data);
                break;
            }
        }           
        if( c == Items.Count)
        {               
            //Missed out, so insert at end.
            Items.Insert(c,data);
        }
    }

    public string GetItemOrder(int index)
    {
        if(index < 0 || index >= Items.Count)
            return null;
        else
            return ((ItemData)Items[index]).ItemOrder;
    }

    private bool bNumeric = false;

    /* Inner class which defines the object that 
     we insert as a list box item */
    class ItemData
    {
        public ItemData(string str1, string str2)
        {
            m_ItemText=str1;
            m_ItemOrder=str2;
        }
        private string m_ItemText;
        private string m_ItemOrder;

        /* Required for list box display purposes */
        public override string ToString()
        {
            return m_ItemText;
        }

        /*
          This method figures out whether the instance object
          is less than the given object. It does this in two 
          different ways depending on whether the order
          has been set to numeric or non-numeric
        */
        public bool IsLess(ItemData d, bool bNum)
        {
            if(bNum)
            {
                int i1 = Convert.ToInt32(m_ItemOrder);
                int i2 = Convert.ToInt32(d.m_ItemOrder);
                return ( i1 < i2 );
            }
            else
            {
                return ( m_ItemOrder.CompareTo(d.m_ItemOrder) < 0 );
            }
        }

        public string ItemOrder
        {
            get
            {
                return m_ItemOrder;
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
GeneralMy vote of 5 Pin
Kanasz Robert27-Sep-12 11:05
professionalKanasz Robert27-Sep-12 11:05 
Generalallow user to enter other item Pin
Member 113345921-Aug-04 5:12
Member 113345921-Aug-04 5:12 
GeneralStill has the same problem as mine... Pin
LongRange.Shooter24-Oct-02 8:50
LongRange.Shooter24-Oct-02 8:50 
GeneralJust some little things... Pin
Anonymous30-Jul-02 23:19
Anonymous30-Jul-02 23:19 
GeneralRe: Just some little things... Pin
Nish Nishant30-Jul-02 23:42
sitebuilderNish Nishant30-Jul-02 23:42 
GeneralRe: Just some little things... Pin
Anonymous26-Jan-03 8:42
Anonymous26-Jan-03 8:42 
QuestionAre you god? Pin
Stefan Spenz30-Jul-02 4:19
Stefan Spenz30-Jul-02 4:19 
AnswerRe: Are you god? Pin
Nish Nishant30-Jul-02 4:25
sitebuilderNish Nishant30-Jul-02 4:25 
AnswerRe: Are you god? Pin
Nish Nishant30-Jul-02 4:39
sitebuilderNish Nishant30-Jul-02 4:39 
AnswerRe: Are you god? Pin
Smitha Nishant30-Jul-02 4:59
protectorSmitha Nishant30-Jul-02 4:59 
Stefan Spenz wrote:
Are you god?

He is not GOD. But I guess sometimes he looks like a greek GOD !

Tweety

It's easy to sit there and say you'd like to have more money. And I guess that's what I like about it. It's easy. Just sitting there, rocking back and forth, wanting that money.

GeneralRe: Are you god? Pin
Nish Nishant30-Jul-02 5:00
sitebuilderNish Nishant30-Jul-02 5:00 
GeneralRe: Are you god? Pin
Smitha Nishant30-Jul-02 5:12
protectorSmitha Nishant30-Jul-02 5:12 
GeneralRe: Are you god? Pin
Nish Nishant30-Jul-02 5:13
sitebuilderNish Nishant30-Jul-02 5:13 
GeneralRe: Are you god? Pin
Shog930-Jul-02 11:23
sitebuilderShog930-Jul-02 11:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.