按两列对Datagridview进行排序

编程入门 行业动态 更新时间:2024-10-28 00:22:45
本文介绍了按两列对Datagridview进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含3列的datagridview。但是我没有将数据源绑定到datagridview。 它具有三列。

I have a datagridview that contain 3 columns. But I hv not bind a datasource to datagridview. It has three columns.

我可以在datagridview中编辑EmpName。

I can edit EmpName in datagridview.

我想在编辑一行后对datagridview中的内容进行排序。

I want to sort the content in the datagridview after i edit a row.

我想首先按EmpName排序,然后按InTime排序。 时间采用AM,PM时间格式(例如:2:00 PM)。

I want to sort first by EmpName and then by InTime. The time is in AM , PM Time format (Ex: 2:00 PM).

我只能按一列对数据进行排序。 我已经使用过,

I can sort data by only one column. I have used,

dgvSchedule.Sort(dgvSchedule.Columns[0],ListSortDirection.Ascending);

但是如何按多列排序。特别是当时间采用AM PM格式时。 请帮助我。

But how to sort by multiple columns. Specially when the time is in AM PM format. Please help me.

谢谢。

推荐答案

以某种方式实现 IComparer :

private class CustomComparer : IComparer { private static int SortOrder = 1; public CustomComparer(SortOrder sortOrder) { SortOrder = sortOrder == SortOrder.Ascending ? 1 : -1; } public int Compare(object x, object y) { DataGridViewRow row1 = (DataGridViewRow)x; DataGridViewRow row2 = (DataGridViewRow)y; int result = row1.Cells["EmpName"].Value.ToString().CompareTo( row2.Cells["EmpName"].Value.ToString()); if ( result == 0 ) { result = DateTime.ParseExact( row1.Cells["InTime"].Value.ToString(), "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay .CompareTo( DateTime.ParseExact( row2.Cells["InTime"].Value.ToString(), "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay); } return result * SortOrder; }

用法是:

dgvSchedule.Sort(new CustomComparer(ListSortDirection.Ascending));

更多推荐

按两列对Datagridview进行排序

本文发布于:2023-10-28 02:37:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按两列   Datagridview

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!