![](/img/trans.png)
[英]How to sort a DataGridView that is bound to a collection of custom objects?
[英]How to Custom Datagridview Sort Like this
我有一个带有列值的Windows Datagridview
id
---
0
0
0
5
2
7
我想升序排序,但零个containg单元将在下面。 像这样-
2
5
7
0
0
0
由于您还没有提到DataGridView
的数据源,因此我展示了一种使用集合的方法。 例如,使用int[]
但它适用于所有:
int[] collection = { 0, 0, 0, 5, 2, 7 };
int[] ordered = collection.OrderBy(i => i == 0).ThenBy(i => i).ToArray();
之所以有效,是因为第一个OrderBy
使用了可以为true
或false
。 由于true
比false
“高”,所有不为0的都排在最前面。 ThenBy
用于非零组的内部排序。
如果那太抽象了,也许您会觉得这更具可读性:
int[] ordered = collection.OrderBy(i => i != 0 ? 0 : 1).ThenBy(i => i).ToArray();
如果您没有为网格使用数据源,则可以使用像这样的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;
}
}
不要忘记将事件处理程序附加到网格视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.