Re: How to perform ListBox search?

Posted by webmaster Guido on November 18, 2000 at 17:09:40:

In Reply to: How to perform ListBox search? posted by Weirghn Ingrad on November 16, 2000 at 20:40:47:

: How to perform String search in List Box?
: Lets say when a user press a Button the aplication performs search for text string that was entered in Edit element, and the the string if found get selected. And how to make Next Search(if one string found, but ListBox contains three strings like were, weres, uwere and user is searching for 'were'?

As I understand it, you are not searching for the first or next item that _begins_ with a search string, but that _contains_ that string.

When a new string is entered in the Editbox "Ed", let's search for the first occurrence. Otherwise, we search for the next occurrence. Let's also search in a "circular" way, meaning: when at the last item of the listbox "LB", wrap around to the beginning of the listbox. Let's suppose also that the search is not case sensitive.

The previous search-string is stored in a global variable. At the beginning of the implementation section, right before the first routine, you write:

  OldSearch: string;

At the first search, right after starting the program, OldSearch must be empty (the first search always starts at the top of the listbox). We also position the listbox at the first item:

procedure TForm1.FormCreate(Sender: TObject);
  OldSearch := '';
  LB.ItemIndex := 0;

The search procedure:

procedure TForm1.Button1Click;
 SearchFor: string;
 StartAt, i: integer;
 Found: Boolean;
  SearchFor := LowerCase(Ed.Text);
  if (SearchFor <> OldSearch) then StartAt := 0
  else StartAt := LB.ItemIndex;
  i := StartAt;
  if (SearchFor <> OldSearch) then
    Found := Pos(SearchFor, LowerCase(LB.Items[i])) > 0
    Found := False;
  while not Found do begin
    inc(i); // next item
    // wrap around if needed
    if i > LB.Items.Count - 1 then i := 0;
    Found := Pos(SearchFor, LowerCase(LB.Items[i])) > 0;
    if i = StartAt then break;
  if Found then LB.ItemIndex := i;
  OldSearch := SearchFor;

Related Articles and Replies: