Search ListBox

Posted by Ch!mera on July 10, 2001

Hi all

I want to search a Delphi ListBox, but only a part of an Item.


An item is:
'set adr0 144.545.365.6546.75.567467'

Search string:
'set adr0'

Re: webmaster Guido on July 16, 2001

I suppose that you want to find the position of the first item that begins with a given search string. You can check each item of the listbox with the Delphi function Pos(SubString, S) that returns the position of a given "substring" in a given string S. It returns 1 or higher if SubString is contained in S, or -1 if SubString is not found in S.

The example function below returns the index of the item that begins with a certain search string. It returns from 0 to the number of items minus one, or it returns -1 if no item is found that begins with SearchStr. We also provided for a safety net in case that the listbox is empty, and we made the checking "case insensitive":

function TForm1.ItemNrBeginsWith(SearchStr: string): integer;
  i, P: integer;
  Result := -1;
  if ListBox1.Items.Count = 0 then exit;
  for i := 0 to ListBox1.Items.Count - 1 do
  if Pos(LowerCase(S), LowerCase(ListBox1.Items[i])) = 1 then begin
    Result := i;

How to use this function:

  ItemNr: integer;
  ItemNr := ItemNrBeginsWith(Edit1.Text);