Mirror

How to add a string and an integer value to the items property of a TListBox (Views: 100)


Problem/Question/Abstract:

How to add a string and an integer value to the items property of a TListBox

Answer:

This requires some type conversions. The TString component has an Objects array along with the string array that can be utilized for the purpose of storing integer data: The data type that the Objects array holds is TObject. In essence it holds a 4 byte pointer value. So to put an integer value in it you would need to type cast that value. For example, the following is adding a string and an integer value of 100 to an items property (TString object) of a Listbox:


Listbox1.Items.AddObject('Text string', TObject(100));


To get the value out do the following:


Result := LongInt(Listbox1.Items.Objects[0]);



This assumes that Result is of type Longint and that the value that were after is at index position 0. Note: Though this works it is never wise to rely on the internal workings of an object. This is trick code and should be well commented.

If you want to keep track of more than one value then a new class can be derived from the TObject base class to hold these values.

type
  ManyValues = class(TObject)
    Value1: Integer;
    Value2: Integer;
  end;
  { ... }

<< Back to main page