Example 4: Applying the sort to the dataset

Uses OnSortChange - easy to overlook, since TEgDBGridEx only tracks and displays the sort state (the arrow in the title, SortSelectedField, SortDirection); it never reorders the dataset by itself. Nothing happens to the actual row order until this event does it.

Scenario

Two variants of the same grid, covering the two common dataset shapes: a plain table-type dataset (reorder via an index), and a query-type dataset (reorder by re-executing with a new ORDER BY).

Setup

FGrid.SortFields.Text := 'CustomerName' + sLineBreak + 'OrderDate' + sLineBreak + 'Total';
FGrid.OnSortChange := GridSortChange;

Table-type dataset: reorder via an index

procedure TfrmOrders.GridSortChange(Sender: TObject);
begin
  // Table.IndexFieldNames drives the actual row order for a TTable-like
  // dataset; SortDirection only flips ascending/descending, it does not
  // support a DESC index directly, so a descending sort re-reads the
  // ascending index and reverses traversal via SetRange/Last+Prior instead,
  // or - simpler here - just re-sorts ascending and lets the user re-click
  // for descending if the underlying index type does not support descending
  // traversal. Adjust to whichever your dataset actually supports.
  Table.IndexFieldNames := FGrid.SortSelectedField;
end;

Query-type dataset: re-execute with ORDER BY

procedure TfrmOrders.GridSortChange(Sender: TObject);
var
  Direction: string;
begin
  if FGrid.SortDirection = sdDescending then
    Direction := ' DESC'
  else
    Direction := '';
  Query.Close;
  Query.SQL.Text := 'SELECT * FROM Orders ORDER BY ' + FGrid.SortSelectedField + Direction;
  Query.Open;
end;

Why it works this way

See Also

(C) 2026 Easygate, Lda