CodeGo.net>在WinForm中DataGridView自定义排序

我的DataGridView控件当前使用绑定数据的Sort属性进行排序,但它没有执行我想要的操作.

我有一列名为Employee的列,显示为“ Firstname Lastname”.

当我按员工排序时,Amy Z_Lastname在John A_Lastname之前列出,这意味着我希望按姓氏排序.

我可以将Employee字符串分成3部分,包括在DataTable中,并将排序设置为“ Lastname,Firstname”,然后隐藏Lastname和Firstname列.

我宁愿学习如何重写默认的IComparer(或其使用的任何方法),以提供有关如何对所需方式进行排序的说明(我想要的答案).

解决方法:

Custom sorting in the DataGridView

The DataGridView knows nothing of this
ranking, of course. The default
sorting scenario (automatic sorting
for a data-bound column) of invoking
DataGridView.Sort() via a column
header mouse click simply delegates to
the IBindingList implementation of
ApplySort() in the list you’ve bound
to the grid. Normally, this list
would be a DataView. Using my
ObjectListView implementation, this
would be a view of a list of arbitrary
business objects. Either way, you end
up comparing the properties of the
items in the list using the
IComparable implementation of the
property type.

Details

The PropertyComparers property exposes
a PropertyComparersCollection, which
is a dictionary of property name keys
and IComparer values. You can replace
the IComparer for a property by using
the PropertyComparersCollection.Add()
method or the indexer (e.g.
view.PropertyComparers[“PropName”] =
myComparer). To revert to the default
IComparable sorting, use the
PropertyComparersCollection.Remove()
method or set the IComparer value to
null via the indexer.

If an IComparer is added to the
PropertyComparers collection, it will
be used for all subsequent sorts until
it is removed from the collection or
it is replaced with another IComparer.
If the ObjectListView is already
sorted when an IComparer is added to
or removed from PropertyComparers, the
view will automatically be re-sorted.

If you want to change multiple
property comparers after the view is
sorted, you can use the ObjectListView
BeginUpdate() and EndUpdate() methods
to suppress the ListChanged and Sort
events until all of the IComparers
have been changed. This prevents
multiple refreshes of the
DataGridView. If the ObjectListView
is not sorted at the time IComparers
are added or removed, no automatic
re-sorting is done.

Note that when sorting on multiple
columns, a custom IComparer can be
used with one sort property, and the
default IComparable sort on another.

例如:

private void radioButtonSortProgram_CheckedChanged(object sender, EventArgs e)

{

    if (this.radioButtonSortProgramAlpha.Checked)

        this.view.PropertyComparers["Program"] = new CustomerProgramComparerAlpha();

    else if (this.radioButtonSortProgramRank.Checked)

        this.view.PropertyComparers["Program"] = new CustomerProgramComparerRank();

    else

        this.view.PropertyComparers.Remove("Program");

}
上一篇:我如何将DataGridViewComboBoxColumn绑定到返回列表的对象的属性/方法?


下一篇:优雅地刷新DataGridView中的数据