Sort items in a ComboBox or ListBox numerically in C#

If you set a ComboBox and ListBox control's Sorted property to true, the control sorts the items it contains. Unfortunately it sorts the items alphabetically according to strings returned by the items' ToString methods. That means if the items are strings that begin with numbers, the items may not be in the most obvious order. For example, alphabetically the value 10 before 2.

To make the items display numerically, sort them first and then display them in a ComboBox or Listbox with Sorted = false.

This example uses the following code to display the same items in ComboBoxes and ListBoxes sorted numerically and alphabetically.

// Load some items.
private void Form1_Load(object sender, EventArgs e)
{
// Make the values.
string[] values = { "1", "2", "3", "10", "11", "100",
 "12", "105", "13", "20", "22", "202", "30" };

// Sort alphabetically.
cboAlphabetic.Sorted = true;
cboAlphabetic.Items.AddRange(values);
cboAlphabetic.SelectedIndex = 0;
lstAlphabetic.Sorted = true;
lstAlphabetic.Items.AddRange(values);
lstAlphabetic.SelectedIndex = 1;

// Sort numerically.
// Convert the values into integers.
var to_int_query = from value in values select int.Parse(value);
int[] numbers = to_int_query.ToArray();

// Sort.
Array.Sort(numbers);

// Display the values.
cboNumeric.Sorted = false;
cboNumeric.DataSource = numbers;
cboNumeric.SelectedIndex = 2;

// Make a copy so the ComboBox and
// ListBox don't share a data source.
lstNumeric.Sorted = false;
int[] numbers2 = new int[numbers.Length];
numbers.CopyTo(numbers2, 0);
lstNumeric.DataSource = numbers2;
lstNumeric.SelectedIndex = 3;
}

The code first makes an array containing the values. It then displays them sorted alphabetically in a ComboBox and a ListBox. The code uses the controls' AddRange methods to copy the values into the controls' Items lists without binding the control to the array. If the code set the controls' DataSource properties equal to the array, then they would share the values and be synchronized. (See the example Link data sources between ComboBoxes and ListBoxes in C#.)

Next the program uses LINQ to copy the values into an array of integers. For each value in the array, it selects the value parsed as an integer.

The code then sorts the array of integers and sets the ComboBox's DataSource property equal to the sorted array.

Finally the code makes a copy of the sorted array and sets the last ListBox's DataSource property equal to the copy. (It uses a copy instead of the same array so these two controls don't share a DataSource.)

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.