BLOG.CSHARPHELPER.COM: Sort items in a ComboBox or ListBox numerically in C#
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.
// 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();
// 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.)
3/29/2012 6:36 AM
WouterH wrote:
There is also a dirty way: you can override the private comparer member of the ObjectCollection ComboBox.Items and assign your own IComarer instance to it. Reply to this
There is also a dirty way: you can override the private comparer member of the ObjectCollection ComboBox.Items and assign your own IComarer instance to it.
Reply to this
I don't think I would call that the dirty way. That's a more flexible approach.
Reply to this