在DataGridView上进行自定义排序

编程入门 行业动态 更新时间:2024-10-14 08:22:48
本文介绍了在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上进行自定义排序

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

发布评论

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

>www.elefans.com

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