Mega Code Archive

 
Categories / Delphi / Examples
 

Looking for text in any part of a field

Title: Looking for text in any part of a field Question: A function to search text in part of a field of any dataset Answer: Looking for text in any part of a field The following function searches for text in any part of a field of any dataset (it can be for example a TTable, TQuery, TADOTable, TADOQuery, TIBTable, TIBQuery, etc.) type TLocateStrOption = (loCaseSensitive, loContinue); TLocateStrOptions = set of TLocateStrOption; function LocateStr(Dataset: TDataset; Field: TField; Str: String; LocateOptions: TLocateStrOptions): boolean; // Searches text in any part of a dataset field. The search can be // case sensitive (option loCaseSensitive) and can start from the // beginning or from the current record (option loContinue). // // Returns True if the string was found (the dataset is positioned // in that record) and False otherwise (the dataset is left in EOF) var ControlsDisabled: boolean; begin ControlsDisabled := Dataset.ControlsDisabled; if not ControlsDisabled then Dataset.DisableControls; try if loContinue in LocateOptions then begin if not Dataset.Eof then Dataset.Next; end else Dataset.First; // Start from the beginning if not (loCaseSensitive in LocateOptions) then Str := UpperCase(Str); while not Dataset.Eof do begin if loCaseSensitive in LocateOptions then begin if Pos(Str, Field.AsString) 0 then break; end else begin if Pos(Str, UpperCase(Field.AsString)) 0 then break; end; Dataset.Next; end; Result := Dataset.Eof; finally if not ControlsDisabled then Dataset.EnableControls; end; end;