Example 4: Applying the sort to the dataset

Uses OnSortChange to apply the order a title click asks for. The grid shows the sort direction in the title, but never reorders the data itself: the dataset does, as it knows how.

Scenario

A click on a title orders the products by that column, ascending, then descending on the next click.

Units

Besides EgFireGrid: System.StrUtils (IfThen, in the second snippet) and the unit of the dataset component (here FireDAC.Comp.Client, for Query1).

The handler

For a FireDAC dataset, IndexFieldNames orders the records in memory, with no new query:

procedure TForm1.Grid1SortChange(Sender: TObject; Column: TEgFireGridColumn; Direction: TEgFireGridSortDirection);
begin
  case Direction of
    fgsAscending:
      Query1.IndexFieldNames := Column.FieldName;
    fgsDescending:
      Query1.IndexFieldNames := Column.FieldName + ':D';
  else
    Query1.IndexFieldNames := '';
  end;
end;

For a large table, the order can instead be given to the server, with a new query:

Query1.Close;
Query1.SQL.Text := 'SELECT * FROM Products ORDER BY ' + Column.FieldName +
  IfThen(Direction = fgsDescending, ' DESC', '');
Query1.Open;

Why it works this way

See Also

(C) 2026 Easygate, Lda