Mirror

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


Problem/Question/Abstract:

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?

Answer:

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);
var
  MyInt, MyStatus: smallint;
  Combine: integer;
begin
  MyInt := 1234;
  MyStatus := 5678;
  Combine := MyInt or (MyStatus shl 16);
  with ListBox1.Items do
  begin
    { store the string and data }
    AddObject('Foobar', pointer(Combine));
    { retrieve the data }
    MyInt := integer(Objects[0]) and $FFFF;
    MyStatus := integer(Objects[0]) shr 16;
  end;
end;

<< Back to main page