简体   繁体   中英

Indexes don't work in FDQuery

I have a FDQuery that feeds data to a grid.
When the user clicks on a column I want the grid to order on that column. Because I want to be able to sort on multiple columns, I cannot use the autosort option of the grid.

I tried the following code in my proof of concept. However it does not work.

procedure TForm31.JvDBGrid1TitleBtnClick(Sender: TObject; ACol: Integer;
  Field: TField);
const
  sDesc = 1;
  sASC = 2;
  sNone = 0;
var
  i: integer;
  SortClause: string;
  AField: TField;
  AIndex: TFDIndex;
begin
  case Field.Tag of
    sDesc: Field.Tag:= sASC;
    sASC: Field.Tag:= sNone;
    sNone: Field.Tag:= sDesc;
  end;
  SortClause:= '';
  FDQuery1.Indexes.BeginUpdate;
  try
    FDQuery1.Indexes.Clear;
    for i:= 0 to JvDBGrid1.Columns.Count - 1 do begin
      AField:= JvDBGrid1.Columns[i].Field;
      if AField.Tag <> sNone then begin
        AIndex:= FDQuery1.Indexes.Add;
        AIndex.Name:= AField.FieldName;
        AIndex.Fields:= AField.FieldName;
        //AIndex.Options:= [soNoCase, soNullFirst, soDescNullLast, soDescending, soUnique, soPrimary, soNoSymbols]
        case AField.Tag of
          sDESC: AIndex.Options:= [soDescNullLast];
          sASC: AIndex.Options:= [];
        end;
        AIndex.Active:= true;
      end;
    end;
  finally
    FDQuery1.Indexes.EndUpdate;
    FDQuery1.Refresh;
  end;
end;

It does not matter whether the Query already has an order by clause or not.

What am I doing wrong?

PS I'd rather not resort to constructing a custom order by clause but I know that's an option.

I think you may be missing a step, namely setting the FDQuery's IndexName to the name of the added index. Apparently. setting the added index's Active property is insufficient.

The following works fine for me against the MS Sql Server pubs database Authors table:

procedure TForm1.AddFDIndex;
var
  AIndex : TFDIndex;
begin
  AIndex := FDQuery1.Indexes.Add;
  AIndex.Name := 'ByCityThenlname';
  AIndex.Fields := 'city;au_lname';
  AIndex.Active := True;
  FDQuery1.IndexName := AIndex.Name;
end;

Btw, I'm not sure what your code is supposed to do if more than one column is tagged to be included in the index, but I'll leave that to you ;=)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM