Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of items in a list box

I want to get an bunch of items from a list box, add them to an array, sort it, then put it back into a different listbox. Here is what I have came up with:

ArrayList q = new ArrayList();
        foreach (object o in listBox4.Items)
            q.Add(o);
        q.Sort();
        listBox5.Items.Add(q.ToString());

But it doesnt work. Any ideas?

like image 458
Codie Vincent Avatar asked Sep 08 '10 11:09

Codie Vincent


People also ask

How to sort items in ListBox c#?

Step 2: Drag the ListBox control from the ToolBox and drop it on the windows form. You are allowed to place a ListBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the ListBox control to sort the elements of the ListBox.

What is ListBox in C#?

ListBox in C# is defined as adding a list of elements to the ListBox to operate on single or multiple elements. Difference between the drop-down box and list box is drop-down box can select only one element at a time but in case of the list box, we can select single or multiple elements at a time.

What is ListBox in Visual Studio?

The ListBox represents a Windows control to display a list of items to a user. A user can select an item from the list. It allows the programmer to add items at design time by using the properties window or at the runtime.


1 Answers

You could just use the ListBox.Sorted built in functionality

  foreach (object o in listBox4.Items)
  {
    listBox5.Items.Add(o);
  }
  listBox5.Sorted = true;

Setting ListBox5.Sorted=true will ensure that the items in the listbox are sorted and any subsequent items added to the listbox will be added in the correct order.

Of course this assumes that you have simple sort requirements as suggested by your example.

like image 84
Chris Taylor Avatar answered Oct 04 '22 23:10

Chris Taylor