10402 : I have integers in a column, I must sort them as numbers not strings

Question

I have a column with integer values, when I click the column head to perform the sorting I get this result:

1
10
11
12
13
2
20
21
22

I need:

1
2
3
4
5
6
7
8
9
10

Answer

This happens on unbinded sort, if you have data from a datasource via databind the sorting comes from the datasource. But in your case you can implement your own comparer:

Add the event in form load:
gantt1.Grid.OnUnBindedSort+=new UnBindedSortHandler(Grid_OnUnBindedSort);
// Implement it like this
private
void Grid_OnUnBindedSort(Grid aGrid, UnBindedSortArgs e)
{
  e.aListToSort.Sort(0,e.aListToSort.Count,
new MyComparer(e.descending,e.aColumn));
}

The MyComparer could look like this (this is really a good thing, you can compare anyway you want):

    class MyComparer: IComparer
    {

      private GridColumn fColumn;
      private bool fdescending;
      public MyComparer(bool descending,GridColumn aColumn)
      {
        fdescending=descending;
        fColumn=aColumn;
      }

      #region IComparer Members

      public int Compare(object x, object y)
      {
        int xint=0;
        int yint=0;
       
        if (y is GridNode)
          yint=int.Parse((y as GridNode).GetCell(fColumn.Index).Content.Value.ToString());
        if (x is GridNode)
          xint=int.Parse((x as GridNode).GetCell(fColumn.Index).Content.Value.ToString());

      
        if (fdescending)
          return xint-yint;
        else
          return yint-xint;
      }

      #endregion
      
    }

Leave a Reply