Search code examples
delphilistlistviewvariableslazarus

Store The Content Of The Selected Line Of a TListBox On a Variable


I'm developing a ebook manager on Lazarus, but I'm having some troubles with a component that I've never used(TListBox). On the TListBox named CategoryList, I have these items:

Literature and Fiction
Romance
Computers and Internet
Poetry
Professional and Technical
Science Fiction and Fantasy
Biographies and Memoirs
Business and Finance
Children's Books
Entertainment
History
Science
Self-Help
Textbooks and Educational Materials
Travel
Westerns

When the user select an item on the CategoryList, I want to store it in a variable, but how can I do this?


Solution

  • If you want the index:

    index := CategoryList.ItemIndex;
    

    If you want the string:

    str := CategoryList.Items[CategoryList.ItemIndex];
    

    To capture the moment the user selects something, you need to register an OnChange event:

    CategoryList.OnChange := CategoryListChange;
    

    Where the CategoryListChange is an event listener:

    procedure TMyForm.CategoryListChange(Sender: TObject);
    begin
      // do something with CategoryList.Items[CategoryList.ItemIndex]
    end; 
    

    You might want to look on some of the posts on this webpage too!