Is it possible to have a custom sort/display order in a combox ? Say I want a special value "MasterValue" before all the others.
+1
A:
The following code will do the trick.
Create a separate list of the items you want to sort and then use AddRange.
comboBox1.Items.Add("Master"); List<String> listToSort = new List<String>(); listToSort.Add("6nd"); listToSort.Add("3nd"); listToSort.Add("5nd"); listToSort.Add("4nd"); listToSort.Add("2nd"); listToSort.Sort(); comboBox1.Items.AddRange(listToSort.ToArray<String>());
Koekiebox
2009-09-04 10:02:29
+2
A:
Instead of adding strings, create a class that implements IComparable and overrides ToString.
Add instances of that class to your ComboBox
Ok but I still want "MasterValue" as displayed value and sort according to the ToString() value of all object except the "MasterValue" that should be on the top. Does your answer do the trick?
Toto
2009-09-04 11:00:28
@Duaner: The idea is that the comboBox sorts the elements calling the CompareTo function of the IComparable interface. What you have to do is create a wrapper around the String class. The ToString returns the String you want in the comboBox and the CompareTo makes sure you have the wanted order. If the String is "MasterValue" the CompareTo always return a < 0 so "MasterValue" is always the first.
2009-09-04 11:09:35
Ok perfect.
Toto
2009-09-04 11:15:12
This didn't work for me in .NET 3.5. The System.Windows.Forms.ComboBox has its internal ItemComparer class which actually calls the GetItemText() property which calls ToString() instead of the IComparable interface.
Esteban Brenes
2010-08-27 02:07:02
+1
A:
Create a data source as a view (i.e. stored procedure) that returns an additional field valued 1.
Then get the data source, and add an additional row to the data view, with the additional field valued at 0.
Then sort the view, by that field initially, and then by the description of the field.
This will always then put your 'Master Value' first, then sort the others alphabetically.
private void PopulateCombo()
{
// get data view that returns 3 columns,
//master sort column set to 1, id, and description //
DataView view = GetSource();
// add a new row to the data source that has column values
// 0 for master sort column (all others are returned 1
// an appropriate ID and a description
// data view columns = master sort column, id, description
view.Table.Rows.Add(new object[] {0, 1, "MasterValue"});
// sort first by master column then description //
view.Sort = "MasterSortColumn ASC, Description ASC";
combo.DataSource = view;
combo.ValueMember = "Id";
combo.DisplayMember = "Description";
}
Jayden
2009-09-04 10:26:08