Developer

Custom Sorting

Introducing


With using Custom Sorting technique inside NextGrid6, cells may be sorted inside Column by any criteria.

Few examples, sort cells inside Column with next criteria: Months by Names, Planets Names by sorting their Sizes, Rome Numbers, Color by Names, etc.


Turning On Custom Sorting


First, custom sorting for Column need to be enabled by setting SortType property of Column to stCustom.


Defining sorting criteria logic


With using our own custom sorting criteria only we can know how Column will be sorted, and we need to help Grid to determine which data will be higher in sorted list and which will be lower. This need to be done inside OnCompare event.

This event have 3 very important parameters. We need to compare Cell1 and Cell2 parameters with using our custom sorting logic, and then set Compare parameter to one of theese values: 1, 0, -1

Value 1 mean that by our sorting logic Cell1 is "larger" than Cell2. Value 0 determine that Cells are equal and -1 determine that Cell2 is "larger" that Cell1.

How to do this?

Here is one very simple example:

procedure TForm1.NextGrid61Compare(Sender: TObject; Cell1, Cell2: INxCell; var Compare: Integer); begin if (Cell1.AsString = 'bigger') and (Cell2.AsString = 'smaller') then Compare := 1 else if (Cell1.AsString = 'smaller') and (Cell2.AsString = 'bigger') then Compare := -1 else Compare := 0; end;
In this example we assume that Column is filled with values: "bigger" and "smaller".

As you may see, we will simply say that value "bigger" will be always "higher" than value "smaller".


Full example


First example is not good when there are 3 or more values to sort. When we have more than 2 values inside cells, using Index function is better solution.

We will need to create following function:

function GetIndex(s: string): Integer; begin // insert logic here end;
This function will simply return Index for some value inside cell. We will compare Index of first Cell with index of second Cell and set Compare parameter:

Now all we need is to add code to our GetIndex function. In our example, we will sort Planets names by their sizes:

implementation var Planets: array[1..9] of string = ('pluto', 'mercury', 'mars', 'venus', 'earth', 'neptune', 'uranus', 'saturn', 'jupiter');
Here we have define one Array with all planets. Please note that we have arrange Planets inside this array from smallest to largest.

Now we only need to assign size Index to each planet. We will made this inside GetIndex function:

function GetIndex(s: string): Integer; var i: Integer; begin s := LowerCase(s); Result := 1; for i := 1 to High(Planets) do begin if s = LowerCase(Planets[i]) then begin Result := i; Exit; end; end; end;
With using custom sorting you can sort column by any criteria you need, such as sorting textual column with non-english Alphabets.

See also