[英]How to Custom Datagridview Sort Like this
I have a windows Datagridview with Column values 我有一个带有列值的Windows Datagridview
id
---
0
0
0
5
2
7
I want ascending sort of this but zero containg cells will be under. 我想升序排序,但零个containg单元将在下面。 Like this-
像这样-
2
5
7
0
0
0
Since you haven't mentioned the datasource of your DataGridView
i show an approach with a collection. 由于您还没有提到
DataGridView
的数据源,因此我展示了一种使用集合的方法。 For example with an int[]
but it works with all: 例如,使用
int[]
但它适用于所有:
int[] collection = { 0, 0, 0, 5, 2, 7 };
int[] ordered = collection.OrderBy(i => i == 0).ThenBy(i => i).ToArray();
This works because the first OrderBy
uses a comparison which can either be true
or false
. 之所以有效,是因为第一个
OrderBy
使用了可以为true
或false
。 Since true
is "higher" than false
all which are not 0 come first. 由于
true
比false
“高”,所有不为0的都排在最前面。 The ThenBy
is for the internal ordering of the non-zero group. ThenBy
用于非零组的内部排序。
If that's too abstract, maybe you find this more readable: 如果那太抽象了,也许您会觉得这更具可读性:
int[] ordered = collection.OrderBy(i => i != 0 ? 0 : 1).ThenBy(i => i).ToArray();
If you are not using data source for your grid, then you can use DataGridView.SortCompare event like this 如果您没有为网格使用数据源,则可以使用像这样的DataGridView.SortCompare事件
void yourDataGridView_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
if (e.Column.Name == "Id" && e.CellValue1 != null && e.CellValue2 != null)
{
var x = (int)e.CellValue1;
var y = (int)e.CellValue2;
e.SortResult = x == y ? 0 : x == 0 ? 1 : y == 0 ? -1 : x.CompareTo(y);
e.Handled = true;
}
}
Don't forget to attach the event handler to your grid view. 不要忘记将事件处理程序附加到网格视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.