Search code examples
delphilistboxpascallazarus

Pascal: How can I select items from ListBox1 to display results in listBox 2?


I am new to Pascal Programming. I have been following online tutorials as close as possible.For my Program, I wish to be able to select an Item from List Box 1 (A country), and have the results(Cities) displayed in list box 2. I know it there is probably a simple solution. Any help is appreciated.

       procedure TForm1.ListBox1Enter(Sender: TObject);
           begin
               ListBox1.Items.Add('America');
               ListBox1.Items.Add('United Kingdom');
               ListBox1.Items.Add('France');
           end;

The results just for example could be America-New York,Washington,Phoenix United Kingdom- York,London,Manchester Spain - Madrid,Barcelona,Valencia


Solution

  • A listbox has an ItemIndex property which tells you the index into its Items[] array of the item which is selected (or -1 if none is);

    So, you can use the ItemIndex to get the text value of an item in the listbox (AString := Listbox1.Items[ListBox1.ItemIndex]) and use that to call Items.Add on the second LB.

    Obviously you can access any value in the listbox's Items[] array in code, regardless of whether it's shown as selected in the gui.

    Note that the Items array of a ListBox, like many other arrays in Delphi, is zero-based.