按两列对Datagridview进行排序 [英] Sort Datagridview by Two Columns

查看:167
本文介绍了按两列对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进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆