Thunder
Thunder

Reputation: 10986

how to sort string as number in datagridview in winforms

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

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

Upvotes: 16

Views: 31566

Answers (4)

Fipomat
Fipomat

Reputation: 21

Your problem is that you sort string values. When you load column you must choose type of values in column like that:

dt.Columns.Add("ColumnName", typeof(int));

Upvotes: 2

user2612427
user2612427

Reputation: 159

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

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

And it will sort correctly

Upvotes: 14

AndiDog
AndiDog

Reputation: 70108

You can register on the SortCompare event, for example:

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... ;)

Upvotes: 20

Mikael Svenson
Mikael Svenson

Reputation: 39697

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() );

Upvotes: 0

Related Questions