# Custom Sorting

# Introducing

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

Few use cases for custom sorting sort months by names, planets hames by sorting their sizes, Roman numbers, colors 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 these 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:

procedureTForm1.NextGrid61Compare(Sender: TObject; Cell1, Cell2: INxCell;varCompare: Integer);beginif(Cell1.AsString = 'bigger') and (Cell2.AsString = 'smaller')thenCompare := 1elseif(Cell1.AsString = 'smaller') and (Cell2.AsString = 'bigger')thenCompare := -1elseCompare := 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:

functionGetIndex(s:string): Integer;begin// insert logic hereend;

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:

varPlanets: array[1..9]ofstring= ('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:

functionGetIndex(s:string): Integer;vari: Integer;begins := LowerCase(s); Result := 1;fori := 1toHigh(Planets)dobeginifs = LowerCase(Planets[i])thenbeginResult := 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.