TreeNodeCustomSort (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example shows how to use the CustomSort method to order a subtree in case-insensitive alphabetical order (either forward or backward). The callback function CompareFunc below calls the global AnsiStrIComp function to perform the actual comparison. This example requires two buttons and a populated TreeView. Customsort only operates on the subtree of the selected node.

Code

function CustomSortProc(Node1, Node2: TTreeNode; Data: Longint): Integer; stdcall;
var val: Integer;
begin
  if Data = 0 then
    val := AnsiStrIComp(Pchar(Node1.Text), PChar(Node2.Text))
  else
    val := -AnsiStrIComp(PChar(Node1.Text), PChar(Node2.Text));
  Exit(val);
end;

{
This procedure can then be used as a parameter to CustomSort
to sort the children of a node.

procedure TForm1.Button1Click(Sender: TObject);
var node: TTreeNode;
begin
  node := TreeView1.Selected;
  node.CustomSort(@CustomSortProc, 0);  { Sorts in ascending order. }
end;

procedure TForm1.Button2Click(Sender: TObject);
var node: TTreeNode;
begin
  node := TreeView1.Selected;
  node.CustomSort(@CustomSortProc, 1);  { Sorts in descending order. }
end;

Uses