views:

233

answers:

2

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 expexted is

7 11 12 23 80 81

+1  A: 

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

AndiDog
bingo ! it works ,Thanksexcept e.CellValue1 and e.CellValue2 should be converted to string.
Thunder
@Thunder: Great! I edited my answer - I included the conversion to string, and `CompareTo` should be more readable.
AndiDog
A: 

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() );
Mikael Svenson
@Mikael IComparer should be System.Collections.IComparer ,further we get gridviewrows in x and y hence it cannot be parsed into int or string,so it doesnt work.
Thunder
@Thunder, IComparer is Sysem.Collections.IComparer. I didn't include the using statements, and you're right about the input. But it could be easily changed to handle gridviewrows and pull out the value.I should have tried this in a solution and not freehand.
Mikael Svenson