Reverse index order for ClientDataSet

I want to reorder the index in a TClientDataSet, the following code looks as if it should do the trick, but does nothing. Is there a good way to reorder the index?

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; 
+6
source share
2 answers

TIndexDef.Options are used when creating indexes. They cannot be used to try to affect an existing index. See Documentation ( highlighting ):

When creating a new index, use Options to specify the attributes of the index. Parameters can contain zero or more TIndexOption ixPrimary, ixUnique, ixDescending, ixCaseInsensitive and ixExpression constants.

When checking the definitions of existing indexes, read โ€œParametersโ€ to determine the parameters used to create the index.

You need to create a separate index with the ixDescending value ixDescending . You can then switch back and forth by simply changing the IndexName property.

+7
source

This is a method that I decided to solve for sorting in both directions. Basically it just creates and frees indexes, but not very pretty, but it works. This is much easier to do with TFDMemTable (if you have access to 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; 
0
source

All Articles