问题描述
当我分配一个列表< MyClass的>
到数据源
A DataGridView的,当我点击列标题,没有任何反应和排序不工作;但如果我使用
数据表
为数据源,排序单击一个标题时,运行完美。
When I assign a List<MyClass>
to DataSource
of a DataGridView
, when I click on column headers, nothing happens and sorting doesn't work; but if I use a DataTable
as data source, the sorting works perfect when a header is clicked.
问题是:哪种集合类型应该被用来启动排序在 DataGridView的
就像它与数据表
当我点击在列标题?
The question is: Which kind of collection types should be used to enable sorting in DataGridView
just like it works with DataTable
when I click on column header?
推荐答案
如何在数据绑定的DataGridView排序作品
当您单击列标题中的数据绑定 DataGridView的
其中它的自动分拣启用,首先它会检查名单的背后在的数据源
属性的,然后使用的检查列表支持排序。然后调用方法对列表进行排序
When you click on a column header in a data-bound DataGridView
which its automatic sorting is enabled, first it checks if the list behind of the DataSource
property is IBindingList
, then using SupportsSorting
checks if the list supports sorting. Then it calls ApplySort
method to sort the list.
当您使用的作为网格的数据源,该数据源后面列表实际上是一个它实现 IBindingList的
的支持排序。
When you use a DataTable
as data source of the grid, the list behind the data source is actually a DataView
which implements IBindingList
that supports sorting.
要对在 DataGridView的
,列表应实施 IBindingList的及其成员这是排序相关
To have automatic support for sorting in a DataGridView
, the list should implement IBindingList
and its members which are related to sort.
启用的的BindingList<排序; T>
要键入的列表实现 IBindingList的
也支持排序,一个不错的选择是从的 。它实现了 IBindingList的
,但它不支持默认的排序。您可以覆盖这其中涉及到排序的方法和属性: SupportsSortingCore
, IsSortedCore
, SortPropertyCore
, SortDirectionCore
和 ApplySortCore
。
To have typed list implementation of IBindingList
which also supports sorting, a good option is deriving from BindingList<T>
. It implements IBindingList
but it doesn't support sorting by default. You can override it's methods and properties which are related to sorting: SupportsSortingCore
, IsSortedCore
, SortPropertyCore
, SortDirectionCore
and ApplySortCore
.
现有的实现
有一些实现办法:
-
实现它在实体框架中使用
SortableBindingList<T>
implementation which is used in Entity Framework.
的这是发表在一个
如果您使用的是实体框架的上的财产 DbSet< T>
返回一个排序的BindingList< T>
If you are using Entity Framework, ToBindingList
method of the Local
property of DbSet<T>
returns a sortable BindingList<T>
.
这篇关于DataGridView的排序点击列标题 - 使用泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!