Sort Datagridview by Two Columns

我的梦境 提交于 2019-12-25 16:55:36

问题


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

EmpName,InTime,OutTime

I can edit EmpName in datagridview.

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

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);

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

Thanks in advance.


回答1:


Implement the IComparer somehow like this:

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;
    }

Usage is:

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


来源:https://stackoverflow.com/questions/21728420/sort-datagridview-by-two-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!