4

I'm working on a TClientDataset that the user can filter at any time based on some criterias. My problem is, we'd like the dataset's cursor to remain positionned "mostly" at the same place after filtering. ("Mostly" in double quote since, of course, it can't stay at the same place if the record is filtered out).

After doing some research, the best I could come up with is the following :

procedure RefreshFilter;
var
  I : Integer;
  sFilter : string;
  vIndexValue: array of TVarRec;
  vIndexValueAsVar : Array of Variant;
begin
  sFilter := GenerateNewFilterExpression;

  if sFilter <> MyDataset.Filter then
  begin
    if MyDataset.IndexFieldCount > 0 then
    begin
      SetLength(vIndexValueAsVar, MyDataset.IndexFieldCount);
      SetLength(vIndexValue, MyDataset.IndexFieldCount);

      for I := 0 to MyDataset.IndexFieldCount - 1 do
      begin
        vIndexValueAsVar[I] := MyDataset.IndexFields[I].AsVariant;
        vIndexValue[I].VType := vtVariant;
        vIndexValue[I].VVariant := @vIndexValueAsVar[I];
      end;
    end;

    MyDataset.Filtered := sFilter <> '';
    Mydataset.Filter := sFilter;

    if MyDataset.IndexFieldCount > 0 then
    begin
      MyDataset.FindNearest(vIndexValue);
    end;
  end;
end;

Even though it works pretty well, I find the solution a bit "bulky". I was wondering if there was a some built-in function or a different approach that might be more elegant and less "heavy".

And please, don't mention bookmarks... Bookmarks don't work properly after changing the active filter, and not at all if your record gets filtered out.

Ken Bourassa
  • 6,363
  • 1
  • 19
  • 28
  • 2
    This looks like a relatively simple task, but there seems to be no reliable way other than you've shown. You cannot rely on `RecNo` nor cursor's sequence number since both gets reindexed when the filter is applied. Bookmarks won't work for records that are filtered out. And what remains really seems to be the index field. [+1ed wondering about a downvote; this is a good question showing a good research effort!] – TLama Sep 08 '14 at 20:57
  • 1
    @TLama - You've mentioned bookmarks. – Sertac Akyuz Sep 08 '14 at 21:10

0 Answers0