如何在winforms中的datagridview中将字符串排序为数字

时间:2021-03-03 15:49:32

I have string column with numbers in a datagridview.It is not bound, I would like to sort it number wise I used

我在datagridview中有数字的字符串列。它没有绑定,我想按照我使用的数字排序

colid.ValueType = typeof(int);
grid.Sort(colid, ListSortDirection.Descending);

but is sorts like string eg:

但是像字符串一样排序,例如:

11
12
23
7
80
81

while the expected is

而预期的是

7
11
12
23
80
81

3 个解决方案

#1


21  

You can register on the SortCompare event, for example:

您可以在SortCompare事件上注册,例如:

private void customSortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    int a = int.Parse(e.CellValue1.ToString()), b = int.Parse(e.CellValue2.ToString());

    // If the cell value is already an integer, just cast it instead of parsing

    e.SortResult = a.CompareTo(b);

    e.Handled = true;
}

...
yourGridview.SortCompare += customSortCompare;
...

I didn't check if that works, but you get the idea... ;)

我没有检查是否有效,但你明白了...;)

#2


6  

You can just convert to Int32 when you assign value to column

将值赋给列时,只需转换为Int32即可

DataGridView.Cells["example"].Value= Convert.ToInt32(text);

And it will sort correctly

它会正确排序

#3


0  

Create a class like:

创建一个类,如:

class Sort : IComparer
{
    public int Compare(object x, object y)
    {
        return -int.Parse((string)x).CompareTo(int.Parse((string)y)); //sort descending
        //return int.Parse((string)x).CompareTo(int.Parse((string)y)); //sort ascending
    }
}

and do

并做

grid.Sort( new Sort() );

#1


21  

You can register on the SortCompare event, for example:

您可以在SortCompare事件上注册,例如:

private void customSortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    int a = int.Parse(e.CellValue1.ToString()), b = int.Parse(e.CellValue2.ToString());

    // If the cell value is already an integer, just cast it instead of parsing

    e.SortResult = a.CompareTo(b);

    e.Handled = true;
}

...
yourGridview.SortCompare += customSortCompare;
...

I didn't check if that works, but you get the idea... ;)

我没有检查是否有效,但你明白了...;)

#2


6  

You can just convert to Int32 when you assign value to column

将值赋给列时,只需转换为Int32即可

DataGridView.Cells["example"].Value= Convert.ToInt32(text);

And it will sort correctly

它会正确排序

#3


0  

Create a class like:

创建一个类,如:

class Sort : IComparer
{
    public int Compare(object x, object y)
    {
        return -int.Parse((string)x).CompareTo(int.Parse((string)y)); //sort descending
        //return int.Parse((string)x).CompareTo(int.Parse((string)y)); //sort ascending
    }
}

and do

并做

grid.Sort( new Sort() );