Posted by Jenny, DelphiLand Team on March 11, 2008
In Reply to Selecting a line from a List Box posted by RussCAp12602 on March 09, 2008: How do I select a line from a List Box? I want to fill a LB from a file, then have the user select a particular line, and have it highlighted.
: Also I want to select a line from within the code and highlight it.
: Is there an easy way to search the Items list for a particular entry?
Suppose that we have ListBox1 with the following 3 items: APPLE, PEAR, BANANA.
The property ItemIndex indicates which item is selected (highlighted). If no item is selected, ItemIndex equals -1. Numbering starts at 0; if the first item is selected then ItemIndex equals 0, the second item gives 1, and so on.
You can set ItemIndex programmatically to select (highlight) an item. For example: if we have ListBox1 with the 3 items "APPLE", "PEAR" and "BANANA", this is the code for selecting "BANANA":
ListBox1.ItemIndex := 2;
To find the index (position) of a particular entry, you use the method Items.IndexOf. To find the index of "PEAR", you use:
P := ListBox1.Items.IndexOf("PEAR"); // P will become 1
Note: it's quite useful that IndexOf is case-insensitive, such that the following code also gives the same result:
P := ListBox1.Items.IndexOf("pear");