Indexes don't work in FDQuery

廉价感情. 提交于 2019-12-11 10:47:36

问题


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?

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


回答1:


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 ;=)



来源:https://stackoverflow.com/questions/35161974/indexes-dont-work-in-fdquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!