How to store additional data in a TListBox along with each item it contains (Views: 100)


In my application I have a TListBox control and I need to store additional data along with each item it contains. The additional data will be an integer variable and a status variable. What is the best way of doing this? Is there some other control I can use?


TListBox objects are pointers, but you can cast a 32-bit integer to a pointer and store its value directly. Therefore, if your "integer variable" and "status variable" can be crammed into 32 bits, you can do this:

procedure TForm1.Button1Click(Sender: TObject);
  MyInt, MyStatus: smallint;
  Combine: integer;
  MyInt := 1234;
  MyStatus := 5678;
  Combine := MyInt or (MyStatus shl 16);
  with ListBox1.Items do
    { store the string and data }
    AddObject('Foobar', pointer(Combine));
    { retrieve the data }
    MyInt := integer(Objects[0]) and $FFFF;
    MyStatus := integer(Objects[0]) shr 16;

<< Back to main page