排序数据绑定组合框的最佳方法是什么?
我对此进行了一些研究,似乎对数据绑定组合框进行排序的唯一方法是对数据源本身(在这种情况下为DataSet中的DataTable)进行排序。
如果是这样,那么问题就变成了对DataTable进行排序的最佳方法是什么?
组合框绑定是在设计器中使用初始化设置的
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. Solution Answer 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");
这将对我们直接从DataTable中检索的所有行进行排序。
回答
如果使用的是DataTable,则可以使用(DataTable.DefaultView)DataView.Sort属性。为了获得更大的灵活性,我们可以使用BindingSource组件。 BindingSource将是我们组合框的数据源。然后,我们可以将数据源从数据表更改为列表,而无需更改组合框的数据源。
myDataTable.DefaultView.Sort = "Field1, Field2 DESC";
回答
排序ComboBox的最简单方法是使用ComboBox.Sorted属性。但是,如果我们正在使用数据绑定,那将不起作用。在这种情况下,我们必须对数据源本身进行排序。
我们可以使用SortedList或者SortedDictionary(均通过键排序),也可以使用DataView。
DataView具有一个Sort属性,该属性接受一个排序表达式(字符串),例如:
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.
在上面的示例中,State和ZipCode都是用于创建DataView的DataTable中的列。
回答
在设置Sort属性而不是表之后,请确保将DefaultView绑定到Controls数据源:
view.Sort = "State, ZipCode DESC";
回答
我意识到我们已经选择了这个问题的答案,但是我建议我们将DataView放置在窗体上,将其绑定到DataSet / DataTable,然后在设计器中的View上设置排序。然后,将组合框绑定到DataView,而不是DataSet / DataTable。
回答
Josh Smith的博客文章回答了这个问题,并全部在XAML中完成。
标题数量不匹配
代码数量不匹配