在DataGridView上进行自定义排序 [英] Custom Sorting on a DataGridView

查看:148
本文介绍了在DataGridView上进行自定义排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO上发现了一些与此问题类似的问题,但没有一个与这个问题相匹配,所以我们开始吧.

I found a few questions similar to this one here on SO, but none that matched this problem, so here we go.

我有一个显示团队成员的DataGridView.在列之一中列出的团队中,所有团队成员均具有分配的角色.例如法律代表",客户经理",助理客户经理"或会计师".

I've got a DataGridView showing members of a team. All the team members have an assigned role within the team listed in one of the columns. Examples could something like be "Legal Representative", "Account Manager", "Assistant Account Manager" or "Accountant".

现在这是有趣的地方.我基本上想按字母顺序对此列上的网格进行排序,但有几个例外.应该始终在顶部列出客户经理",如果有的话,后面应该是助手客户经理".

Now here's where it gets interesting. I basically want to sort the grid on this column alphabetically, with a couple of exceptions. The "Account Manager" should always be listed at the top, followed by the "Assistant Account Manager" if there is one.

此时对象和网格都可以使用,并且已经在生产版本中发布了一段时间,所以我不想在此基础上做更多的工作.

The objects and grid are all operational at this point, and have been in production release for some time, so I don't want to do more work on this than strictly necessary.

有没有简单的方法可以做到这一点?我认为我必须以编程方式进行操作...

Is there an easy way to do this? I assume I have to do it programatically...

一些伪代码来阐明:

if (memberRole == 'Account Manager') 
{
    //put in top row
}
else if (memberRole == 'Assistant Account Manager')
{
    //put in second row 
}
else
{
    //sort remaining rows alphabetically
}

我使用Visual Studio 2008在C#.NET中完成工作.

I do my work in C# .NET using Visual Studio 2008.

推荐答案

您可以捕获datagridview的SortCompare事件:

You can capture the SortCompare event of your datagridview:

    private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        string cell1, cell2;

        if (e.Column == "Your_Column")
        {
            if (e.CellValue1 == null) cell1 = "";
            else cell1 = e.CellValue1.ToString();

            if (e.CellValue2 == null) cell2 = "";
            else cell2 = e.CellValue2.ToString();

            if (cell1 == "Account Manager") { e.SortResult = -1; e.Handled = true; }
            else
            {
                if (cell2 == "Account Manager") { e.SortResult = 1; e.Handled = true; }
                else
                {
                    if (cell1 == "Assistant Account Manager") { e.SortResult = -1; e.Handled = true; }
                    else
                    {
                        if (cell2 == "Assistant Account Manager") { e.SortResult = 1; e.Handled = true; }
                    }
                }
            }
        }
    }

这篇关于在DataGridView上进行自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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