我想要反转TClientDataSet中索引的顺序,下面的代码看起来应该做的但是什么都不做。有没有一种很好的方法来扭转索引的顺序?
procedure TForm8.Button1Click(Sender: TObject);
var
index: TIndexDef;
begin
index := ClientDataSet1.IndexDefs.Find('LengthIndex');
if ixDescending in index.Options then
index.Options := index.Options - [ixDescending]
else
index.Options := index.Options + [ixDescending];
end;
答案 0 :(得分:7)
TIndexDef.Options
。它们不能用于尝试影响现有索引。请参阅documentation(强调我的):
创建新索引时,使用“选项”指定索引的属性。选项可以包含零个或多个TIndexOption常量ixPrimary,ixUnique,ixDescending,ixCaseInsensitive和ixExpression。
检查现有索引的定义时,请阅读选项以确定用于创建索引的选项。
您需要创建一个单独的索引,并设置ixDescending
值。然后,您只需更改IndexName
属性即可来回切换。
答案 1 :(得分:1)
这是我最终决定在两个方向进行排序的方法。基本上它只是创建和释放索引,不是非常漂亮但有效。使用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;