Re: Find string in Delphi listbox


[ DelphiLand FAQ ]

Posted by webmaster Guido on April 26, 2004

In Reply to: Find string in Delphi listbox posted by P14347 Pete Lavigne on April 26, 2004

: I have a listbox that I fill with lines from a textfile with the LoadFromFile('c:\data\data.txt') function. That works fine. But now I want to find a string of this listbox. The string is typed in an edit-component. Can you help me with a code example?
----------

If you want to find an exact string, then you can use the method IndexOf(SearchString). This is case insensitive, so you can find "cat" as well as "CAT" or "cAt". Example:

procedure TformStringsValues.Button1Click(Sender: TObject);
var
  I: integer;
  TheString: string;
begin
  TheString := Edit1.Text;
  I := Listbox1.Items.IndexOf(TheString);
  if I > -1 then 
    Label1.Caption := 'Item nr ' + IntToStr(I)
  else
    ShowMessage('Not Found: ' + TheString);
end;

If you want to find an item by only giving the beginning of the string, you have to scan the items one by one in your source code.

The following example finds and displays the first item that starts with a given string. Note that it is case-sensitive.

procedure TformStringsValues.Button1Click(Sender: TObject);
var
  I: integer;
  TheString: string;
  Found: Boolean;
begin
  TheString := Edit1.Text;
  I := 0;
  repeat
    Found := Pos(TheString, Listbox1.Items[I]) = 1;
    if not Found then inc(I);
  until Found or (I > Listbox1.Items.Count - 1);
  if Found then
    Label1.Caption := 'Item nr ' + IntToStr(I)
  else
    ShowMessage('Not Found: ' + TheString);
end; 

Related Articles and Replies:


[ DelphiLand FAQ ]