Question

I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case).

If that is the case then the question becomes what is the best way to sort a DataTable?

The combo box bindings are set in the designer initialize using

myCombo.DataSource = this.typedDataSet;
myCombo.DataMember = "Table1";
myCombo.DisplayMember = "ColumnB";
myCombo.ValueMember = "ColumnA";

I have tried setting

this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC";
But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.

Was it helpful?

Solution

If you're using a DataTable, you can use the (DataTable.DefaultView) DataView.Sort property. For greater flexibility you can use the BindingSource component. BindingSource will be the DataSource of your combobox. Then you can change your data source from a DataTable to List without changing the DataSource of the combobox.

The BindingSource component serves many purposes. First, it simplifies binding controls on a form to data by providing currency management, change notification, and other services between Windows Forms controls and data sources.

OTHER TIPS

You can actually sort the default view on a DataTable:

myDataTable.DefaultView.Sort = "Field1, Field2 DESC";

That'll sort any rows you retrieve directly from the DataTable.

Make sure you bind the DefaultView to the Controls Datasource, after you set the Sort property, and not the table:

myCombo.DataSource = this.typedDataSet.Tables["Table1"].DefaultView;
myCombo.DisplayMember = "ColumnB";
myCombo.ValueMember = "ColumnA";

Josh Smith has a blog post that answers this question, and does it all in XAML.

Does the data need to be in a DataTable? Using a SortedList and binding that to a combo box would be a simpler way.

If you need to use a DataTable you can use the Select method to retrieve a DataView and pass in a sort parameter.

DataView dv = myDataTable.Select("filter expression", "sort");

The simplest way to sort a ComboBox is to use the ComboBox.Sorted property. However, that won't work if you're using data binding. In that case you'll have to sort the data source itself.

You can use either a SortedList or SortedDictionary (both sort by the Key), or a DataView.

The DataView has a Sort property that accepts a sort expression (string) for example:

view.Sort = "State, ZipCode DESC";

In the above example both State and ZipCode are columns in the DataTable used to create the DataView.

I realize that you've already chosen your answer to this question, but I would have suggested placing a DataView on your form, binding it to your DataSet/DataTable, and setting the sort on the View in the designer. You then bind your combobox to the DataView, rather than the DataSet/DataTable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top