简体   繁体   中英

How to Custom Datagridview Sort Like this

I have a windows Datagridview with Column values

id
---
0
0
0
5
2
7

I want ascending sort of this but zero containg cells will be under. 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. For example with an int[] but it works with all:

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 . Since true is "higher" than false all which are not 0 come first. The ThenBy is for the internal ordering of the non-zero group.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM