Search code examples
delphidelphi-7

How to store a Integer in a TObject property and then show that value to the user?


Of course, this piece of code will not compile. First I need to cast a TObject value to Integer. Then, read it as a string. What function should I use?

for i := 1 to 9 do begin
    cmbLanguage.Items.AddObject(Format('Item %d', [i]), TObject(i));
end;

cmbLanguage.ItemIndex := 2;

ShowMessage(cmbLanguage.Items.Objects[cmbLanguage.ItemIndex]);

Or maybe it's possible to use String instead of Integer in the first place?


Solution

  • cmbLanguage.Items.AddObject(Format('Item %d', [i]), TObject(i));
    

    Here you are adding an item with an "object" which is actually an integer (i) casted to a TObject.

    Since you are actually storing an int in the object field, you can just cast it back to Integer, then convert that to a string:

    ShowMessage(IntToStr(Integer(cmbLanguage.Items.Objects[cmbLanguage.ItemIndex])));
    

    Note that you are not really converting anything here, you're just pretending that your integer is a TObject so the compiler doesn't complain.