Focus item on Listbox with Delphi

Asked

Viewed 923 times

-2

The following code only works if you type the full string, I would like to modify the code to also focus on the listbox when part of the text is typed autocomplete style

procedure Tform1.Edit1Change(Sender: TObject);
var
i: Integer;
begin
i := ListBox1.Items.IndexOf(Edit1.Text);
if i>= 0 then
begin
ListBox1.ItemIndex:= ListBox1.Items.IndexOf(Edit1.Text);
end;
end;

3 answers

1


In this case you need to scroll through the list in a repeat loop and check item by item, as there is no method for partial searching in the Tlistbox Items property. Example:

procedure TForm1.Edit1Change(Sender: TObject);
var
  i: integer;
begin
  for i := 0 to ListBox1.Items.Count - 1 do
  begin
    if Pos(Edit1.Text, ListBox1.Items[i]) > 0 then
    begin
      ListBox1.ItemIndex := i;
      break; //pra evitar que o resto da lista seja percorrido, dando foco no primeiro item encontrado
    end;
  end;
end;

0

Try the following

uses System.StrUtils,
...
procedure TForm1.FormCreate(Sender: TObject);
begin
  with ListBox1.Items do
    begin
      Add('Good morning!');
      Add('Hi, welcome to StackOverflow');
      Add('Foo Bar');
    end;
end;

procedure TForm1.Edit1Change(Sender: TObject);
Var
  I: Integer;
begin
  for I := 0 to ListBox1.Count-1 do
    begin
      if ContainsText(ListBox1.Items[I], Edit1.Text) then
        begin
          ListBox1.ItemIndex:= I;
          Break;
        end
          else
            ListBox1.ItemIndex:= -1;
    end;
end;

0

For what you want, you may only lack the use of the Leftstr function. Something like:

uses strutils;

procedure TForm1.Edit1Change(Sender: TObject);
var
  i: integer;
  txtLen:integer;
begin
  //Guardar tamanho de string digitada
  txtLen:=Length(Edit1.Text);
  for i := 0 to ListBox1.Items.Count - 1 do
     if length(ListBox1.Items[i])>=txtLen then
        if LeftStr(ListBox1.Items[i],txtLen) = Edit1.Text then
        begin
           ListBox1.ItemIndex := i;
           break;       
        end;
end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.