Search code examples
delphilistboxfiremonkeydelphi-10.2-tokyo

How to find an Item's index in a Firemonkey TListBox?


My goal is to update the ItemIndex of a TListBox, in a way that when programmatically adding an item to the list, the corresponding line is outlined on the TListBox.

I've tried:

with MyLstBox do begin
  ItemIndex := -1;
  for ind := 0 to Pred (Items.Count) do
    if InsertedString = Items [ind]) then begin
      ItemIndex := Ind;
      Break;
    end;
end;

This code outlines the item that was just inserted, but also maintains the outline of the previous inserted item.

MultiSelect is set to False, so in principle, only one item should be outlined.


Solution

  • The Items property is a TStrings object. You can use the TStrings.IndexOf() method instead of a manual loop:

    MyLstBox.ItemIndex := MyLstBox.Items.IndexOf(InsertedString);
    

    When you add a new item to the ListBox, the TStrings.Add() method returns the index of the new item:

    MyLstBox.ItemIndex := MyLstBox.Items.Add(InsertedString);