Search code examples
delphic++builderfiredac

What is the proper way to query a FireDac based TDBGrid to get a count of matching records base on a given critera?


I'm using a FireDac TFDQuery connected to SQLite database with a TDBGrid. When a button is clicked on the toolbar I would like to run a query to get a count of records matching a given criteria without affecting the TDBGrid. How is that designed to be done in this scenario?

TIA!!


Solution

  • If you want an alternative that can be calculated entirely within your application, without having to issue a new command against your server, then you can temporarily clone your dataset.

    That Clone won't affect your TDBGrid, so you can filter by whatever condition you need and return the number of records that fulfil that condition.

    Example:

    procedure MyButtonClick(Sender: TObject);
    var MyClone: TDataset;
    begin
      MYClone := MyQuery.GetClonedDataset(False);
      MyClone.Filter := 'FieldName = ' + QuotedStr(SearchValue);
      MyClone.Filtered := True;
      ShowMessage(MyClone.RecordCount.ToString + ' records found');
      MyClone.Free;
    end;
    

    This is also very useful when you work in CachedUpdates mode, because it will count correctly your records on screen even if they still have not been applied to the database.