Library Vcl NextSuite 6 NextGrid6 Articles Custom Sorting

Custom Sorting

Introduction

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.

Months sorting

Turning on Custom Sorting

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

SortType

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:

pas
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".

alt text

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:

pas
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:

pas
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:

pas
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.

Sign in