Posted by John, DelphiLand Team
In Reply to Why use the OnFilterRecord event? posted by Phil Birell
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); var CombinedFields: string; begin CombinedFields := UpperCase(Books.FieldByName('Title').AsString + Books.FieldByName('SubTitle').AsString + Books.FieldByName('Description').AsString); Accept := (Pos('SCIENCE', CombinedFields) > 0); end;
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!