Use of OnFilterRecord event

Posted by John, DelphiLand Team

In Reply to Why use the OnFilterRecord event? posted by Phil Birell

: It seems that with an OnFilterRecord event handler I can do the same as with the Filter property, only it's more complicated.
: I have to write explicitly which dataset and wich fields to use (such as Books.FieldByName('Title').AsString = ...)
: If I want to simulate a case-insensitive filter, I found out that I must use the function UpperCase(). And also the wildcard character * doesn't work.
: So what's it good for? Am I missing something?

The OnFilterRecord event fires each time when filtering of a Delphi TDataset (TTable, TClientDataSet,...) is enabled and when another record becomes the current record. It's for filtering records that would be difficult or impossible to set up with the Filter property. Here's a typical example: let's say that we display the records of a dataset Books in a DBGrid.

1. Make the Filter property empty, set Filtered to True and navigate to the first record

Books.Filter := '';
Books.Filtered := True;
Books.FindFirst; // go to first record that fits Filter 

Without BooksFilterRecord (see below) that "first" record would be the first physical record of the dataset, or the first record given by an index. But with BooksFilterRecord...:

2. In the event handler BooksFilterRecord we set the parameter Accept to TRUE for the records that we want to show. The source code example is for records that contain the word 'SCIENCE' in the field TITLE, or in SUBTITLE or in DESCRIPTION.

procedure TForm1.BooksFilterRecord(DataSet: TDataSet; var Accept: Boolean);
  CombinedFields: string;
  CombinedFields := UpperCase(Books.FieldByName('Title').AsString + 
    Books.FieldByName('SubTitle').AsString + 
  Accept := (Pos('SCIENCE', CombinedFields) > 0);

Note: we can't use the wildcard character (*) such as in in Books.Filter. But what we do here with the function Pos() is much more powerful: the string "science" is detected in ANY position, not only at the beginning of a field!