If you need to programmatically select an item in a ListBox from code in Delphi 5. There is probably another easier way to do it with newer version of Delphi, but I have to maintain a program written in Delphi 5. So, here’s how you do it.
ListBox1.ItemIndex := 2; {This selects a specified item, in this case itemindex 2}
If ListBox1.Selected[ListBox1.ItemIndex] Then Do
strItemText := ListBox1.Items.Strings[ItemIndex];
To get the count of the items in the ListBox:
procedure TForm1.Button1Click(Sender: TObject); begin if ListBox1.Items.Count > 0 then begin Listbox1.Selected[0]:= True; end; end
To programmatically select an item or items:
procedure TForm1.FormShow(Sender: TObject);
begin
ListBox1.ItemIndex:=0;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Reselect: Integer;
begin
if (Edit1.Text = '') or (ListBox1.ItemIndex = -1) then
exit;
Reselect := ListBox1.ItemIndex;
ListBox1.Items[ListBox1.ItemIndex] := Edit1.Text;
ListBox1.ItemIndex := Reselect;
end;
To search the string in the list of items:
procedure TformStringsValues.Button1Click(Sender: TObject); var I: integer; TheString: string; begin TheString := Edit1.Text; I := Listbox1.Items.IndexOf(TheString); if I > -1 then Label1.Caption := 'Item nr ' + IntToStr(I) else ShowMessage('Not Found: ' + TheString); end;
If you want to find an item by only giving the beginning of the string, you have to scan the items one by one in your source code (case-sensitive).
procedure TformStringsValues.Button1Click(Sender: TObject); var I: integer; TheString: string; Found: Boolean; begin TheString := Edit1.Text; I := 0; repeat Found := Pos(TheString, Listbox1.Items[I]) = 1; if not Found then inc(I); until Found or (I > Listbox1.Items.Count - 1); if Found then Label1.Caption := 'Item nr ' + IntToStr(I) else ShowMessage('Not Found: ' + TheString); end;
Leave a Reply