SQL and TQuery

  1. Finding a record in a TQuery

Finding a record in a TQuery

How do you 'Find' a record in a TQuery?
[David G. Edwards, dedwards@athensnet.com]

I use something like this, but it could use some exception handling. When the user presses the "Find" button, it's OnClick event handler calls SearchName.


Declare FindSearch : Boolean and initialize it to true.

 


function LookForString(target, source : string) : boolean;
{ if Ignoring case, convert source and target to all upper case before
calling pos }
begin
  LookForString:= pos(target, source);
end;

procedure SearchName(searchtype : string; stringtofind : string);
var
  OldCursor : TCursor;
  CurrentPos : TBookmark;
  found: boolean;
begin
  if Form1.Query1.State=dsEdit then Form1.Query1.Post;
  if StringToFind='' then exit;
  OldCursor:= Screen.Cursor;
  Screen.Cursor:= crHourGlass;
  with Form1 do
    begin
      CurrentPos:= Query1.GetBookmark;
      Query1.DisableControls;
      found:= false;
      if searchtype <> 'prev' then { first or next }
        begin
          if searchtype = 'first' then Query1.First
          else if not Query1.EOF then Query1.Next;
          while (not Query1.EOF) and (not found) do
            begin
              if LookForString(StringToFind, MemberName)<>0 then found:= true;
              if not found then Query1.Next;
            end;
          end
      else
        begin { prev }
          if not Query1.BOF then Query1.Prior;
          while (not Query1.BOF) and (not found) do
            begin
              if LookForString(StringToFind, MemberName)<>0 then
              found:= true;
              if not found then Query1.Prior;
            end;
        end;
      Screen.Cursor:= OldCursor;
      if found then
        begin
          FindSearch:= false;
          ChangeFindCaption;
          UpdateStatusLabel;
        end
      else
        begin
          MessageDlg('No more matching members found.', mtInformation,
[mbOK], 0);
          Query1.GotoBookmark(CurrentPos);
        end;
      Query1.EnableControls;
      Query1.FreeBookmark(CurrentPos);
    end; { of with Form1 }
end;

procedure TForm1.FindButtonClick(Sender: TObject);
begin
    if FindSearch then SearchName('first', Page0Edit.Text)
    else SearchName('next', Page0Edit.Text);
end;


Please email me and tell me if you liked this page.