What is the best way to sort data combo box?

I have worked a bit on this, and it seems that the only way to sort the data combo box is to sort the data source itself (DataTable in the DataSet in this case).

If so, then the question will be the best way to sort a DataTable?

List binding is specified in the constructor initialization using

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

I 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.
+3
source share
7 answers

If you use a DataTable, you can use the (DataTable.DefaultView) DataView.Sort property. For more flexibility, you can use the BindingSource component. BindingSource will be the DataSource of your combobox. Then you can change the data source from DataTable to List without changing the DataSource in the drop-down list.

The BindingSource component serves many purposes. First, it makes it easy to link form controls to data, providing currency controls, modifying notifications, and other services between Windows Forms controls and data sources.

+6
source

In fact, you can sort the default view in a DataTable:

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

This will sort any rows you retrieve directly from the DataTable.

+2
source

Make sure you bind DefaultView to the Controls data source after setting the Sort property, not the table:

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

Should the data be in a DataTable? Using a SortedList and binding to a combo box will be an easier way.

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

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

The easiest way to sort ComboBox is to use the ComboBox.Sorted property. However, this will not work if you use data binding. In this case, you will have to sort the data source yourself.

You can use either SortedList , or SortedDictionary (both sorted by key) or 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.

0
source

I understand that you have already chosen your answer to this question, but I would suggest placing a DataView in your form, binding it to your DataSet / DataTable and setting the sort in the view in the designer. Then you bind your combobox to a DataView, not a DataSet / DataTable.

0
source

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

0
source

Source: https://habr.com/ru/post/1415005/


All Articles