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.
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).
FGrid.SortFields.Text := 'CustomerName' + sLineBreak + 'OrderDate' + sLineBreak + 'Total';
FGrid.OnSortChange := GridSortChange;
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;
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;
SortFields,
nor for a click that re-selects the same field and direction already
active - no need to guard against redundant re-sorts inside the
handler.SortSelectedField is already validated
by the time this fires: it is always one of the field names in
SortFields, so it is safe to use directly in a query string
or IndexFieldNames assignment without re-checking it here -
though it is still a plain string built into SQL, so keep
SortFields restricted to real column names, not user
input.TQuery starts back at the first row; if that
matters, capture and restore a bookmark or a primary-key value around
Query.Close/Query.Open, the same as any other
dataset re-query.