Focus item in Listbox with Delphi

-2

The following code works only if you enter the full string, I would like to modify the code to also focus on the listbox when some 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;
    
asked by anonymous 12.10.2018 / 23:24

3 answers

1

In this case, you have to scroll through the list in a loop and check item by item, as there is no partial search method in the Items property of the TListBox. 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;
    
13.10.2018 / 22:56
0

For what you want, you may only need to use 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;
    
14.10.2018 / 23:48
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;
    
19.10.2018 / 09:17