这是我最终确定的双向排序方法。基本上它只是创建和释放索引,不是很漂亮但可以工作。使用TFDMemTable更容易做到(如果您可以访问 FireDAC)
type
TSortByFieldOption = (ForceAscending, ForceDescending);
TSortByFieldOptions = set of TSortByFieldOption;
procedure SortClientDataSetByField(cds : TClientDataSet; FieldName : String; Options : TSortByFieldOptions = []);
const
IndexName = 'GridSort';
var
i: integer;
index: TIndexDef;
OldOrder: string;
IndexOptions : TIndexOptions;
begin
cds.DisableControls;
try
i := cds.IndexDefs.IndexOf(IndexName);
if i <> - 1 then
begin
index := cds.IndexDefs.Find(IndexName);
OldOrder := index.Fields;
try
cds.DeleteIndex(IndexName);
except;
OutputDebugString('no index?');
//there seem to be conditions where the index does not exist but
end;
index.Free; //delete index for some reason does not free the index
indexOptions := index.Options;
end else
IndexOptions := [ixDescending];
index := cds.IndexDefs.AddIndexDef;
index.Name := IndexName;
index.Fields := FieldName;
if ForceAscending in Options then
index.Options := []
else if ForceDescending in Options then
index.Options := [ixDescending]
else if OldOrder = FieldName then
begin
if (IndexOptions = [ixDescending]) then
index.Options := []
else
index.Options := [ixDescending];
end;
cds.IndexName := IndexName;
finally
cds.EnableControls;
end;
end;