Recent

Author Topic: Incremental Search for the TListBox  (Read 7677 times)

wiri17200

  • Newbie
  • Posts: 3
Incremental Search for the TListBox
« on: August 22, 2009, 08:48:25 pm »
Hello

I wanted to be able to search in a listbox. Googled  and found:
http://delphi.about.com/od/vclusing/a/lb_incremental.htm

this however doesnot seem to work in lazarus.  Even replaced the LB_SELECTSTRING  with the numericvalue 396

Being a newbie at lazarus/free pascal programming I am at a loss. 

Henk

JimR

  • New Member
  • *
  • Posts: 11
Re: Incremental Search for the TListBox
« Reply #1 on: November 21, 2009, 06:13:16 am »
This will search a ListBox and give you the index location if found.  There may be a better way to get there, but till you find it, this does work.  1 is added to the location because the ListBox starts numbering at 0.  Put ListBox1, Button1, Label1, and Edit1 on your page to turn this.
Hope it helps.

procedure TForm1.FormCreate(Sender: TObject);
var Lp1 : Integer;
begin
// put 3000 entries into the listbox to have something there.[/font]
for Lp1 := 1 to 3000 do         
  begin
  ListBox1.Items.Add(IntToStr(Lp1))
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
var Lp1, Num : Integer;
begin
Num := -1;
 // search the listbox for a match to edit1.text
for Lp1 := 0 to ListBox1.Items.Capacity - 1 do 
  begin
  if ListBox1.Items.Strings[Lp1] = Edit1.Text then
    Num := Lp1;
  end;
// display results of search.
if Num >= 0 then
  Label1.Caption := 'Found at : ' + IntToStr(Num + 1)
  else
  Label1.Caption := 'Not Found';
 // highlights the listbox entry found.
ListBox1.ItemIndex:= Num;           
end;

Bandbaz

  • New Member
  • *
  • Posts: 40
Re: Incremental Search for the TListBox
« Reply #2 on: November 21, 2009, 09:57:47 am »
Simple:

Code: [Select]
Listbox1.Itemindex := Listbox1.Items.Indexof(Edit1.Text);

Index of the first item is 0

If there is no "Edit1.Text" in Listbox1.Items, result of Indexof() is -1
And when you set Listbox1.Itemindex to -1, All Items will be deselect. (There is a bug here!)

JimR

  • New Member
  • *
  • Posts: 11
Re: Incremental Search for the TListBox
« Reply #3 on: November 21, 2009, 02:22:22 pm »
No bug, that is what is was suppose to do.  If the item searched for in the list exists, it is highlighted, else nothing is highlighted.

I mentioned that the listbox starts at 0 and that I added a 1 to change it so the 3rd item in the list would be 3 instead of 2.  You can always drop the +1 to the itemindex if that suits you.

Bandbaz

  • New Member
  • *
  • Posts: 40
Re: Incremental Search for the TListBox
« Reply #4 on: November 22, 2009, 12:46:06 pm »