AABBbaby

导航

DevExpress WinForms中文教程:Data Grid - 如何自定义排序和非排序列?

DevExpress WinForms拥有180+组件和UI库,能为Windows Forms平台创建具有影响力的业务解决方案。DevExpress WinForms能完美构建流畅、美观且易于使用的应用程序,无论是Office风格的界面,还是分析处理大批量的业务数据,它都能轻松胜任!

在本教程中,您将学习如何实现自定义排序算法来对Birth Date列的值进行排序,而不考虑日期的年份部分,从而获得组织中所有生日的正确排序列表,同时还将学习针对包含不可排序数据(如图像)的列启用排序的技术。

获取DevExpress WinForms v25.1正式版下载

DevExpress技术交流群11:749942875      欢迎一起进群讨论

默认操作

如果单击Birth Date列标题,默认算法将首先考虑年、月、天对日期进行排序。如您所见,该列表显示1月份的生日,然后是5月份的生日,然后又是1月份的生日,因为它们是按年份排序的。

DevExpress WinForms中文使用教程图集
实现自定义排序逻辑

本教程实现了一个自定义排序逻辑,该逻辑将忽略年份部分,并给出仅按月份和日期排序的生日列表。

首先,将列的GridColumn.SortMode属性设置为ColumnSortMode.Custom

DevExpress WinForms中文使用教程图集

之后,选择网格视图并处理它的ColumnView.CustomColumnSort事件。

要处理的列由事件的CustomColumnSortEventArgs.Column参数指定,事件处理程序比较使用CustomColumnSortEventArgs.Value1CustomColumnSortEventArgs.Value2参数指定的两个值,自定义比较的结果被设置为CustomColumnSortEventArgs.Result参数。这个例子比较了生日月份,如果第一个月的数字大于第二个月的数字,则Result参数设置为1,如果第一个月的数字小于第二个月的数字,则将Result参数设置为-1。如果值相等,比较天数。

事件的CustomColumnSortEventArgs.Handled参数被设置为true,以防止在事件执行后调用默认的比较机制。

C#

private void gridView_CustomColumnSort(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnSortEventArgs e) {
if (e.Column.FieldName == "BirthDate") {
e.Handled = true;
int month1 = Convert.ToDateTime(e.Value1).Month;
int month2 = Convert.ToDateTime(e.Value2).Month;
if (month1 > month2)
e.Result = 1;
else
if (month1 < month2)
e.Result = -1;
else e.Result = System.Collections.Comparer.Default.Compare(Convert.ToDateTime(e.Value1).Day, Convert.ToDateTime(e.Value2).Day);
}
}

运行应用程序并单击Birth Date列标题,单元格值现在基于月份和日期比较进行排序,排序顺序忽略年份。

DevExpress WinForms中文使用教程图集
实现非排序列的排序算法

GridControl 可以包含显示不可排序数据(如图像)的列。

Photo列使用PictureEdit就地编辑器显示图像,单击其标题时不会发生任何事情。但是,您也可以为此列启用数据排序。

首先,选择Photo列,展开它的GridColumn.OptionsColumn属性,并将OptionsColumn.AllowSort设置为true。然后,将其GridColumn.SortMode属性设置为ColumnSortMode.Custom

将以下代码添加到ColumnView.CustomColumnSort事件处理程序中。当Photo列的数据排序时,数据实际上将根据First Name列排序。在数据源级别使用事件的CustomColumnSortEventArgs.ListSourceRowIndex1CustomColumnSortEventArgs.ListSourceRowIndex2参数访问列值,CustomColumnSortEventArgs.Handled参数被设置为true,表示已经处理了比较操作。

C#

private void gridView_CustomColumnSort(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnSortEve
// ...
if (e.Column.FieldName == "Photo") {
e.Handled = true;
DataRowView dr1 = (gridView.DataSource as BindingSource)[e.ListSourceRowIndex1] as DataRowView;
DataRowView dr2 = (gridView.DataSource as BindingSource)[e.ListSourceRowIndex2] as DataRowView;
e.Result = System.Collections.Comparer.Default.Compare(dr1["FirstName"], dr2["FirstName"]);
}
}

运行应用程序并单击Photo列标题,网格数据现在根据FirstName列中的值排序。

DevExpress WinForms中文使用教程图集

posted on 2025-10-11 10:19  AABBbaby  阅读(4)  评论(0)    收藏  举报