Lazarus

Programming => General => Topic started by: noszone on June 21, 2021, 07:00:29 am

Title: Populate combobox with values and custom indexes
Post by: noszone on June 21, 2021, 07:00:29 am
I am quite new in objects and pointers, can anyone please advise how to populate combobox with values and custom indexes. For example:

Code: Pascal  [Select][+][-]
  1. cb1.Items.AddObject(value1, customIndex25);
  2. cb1.Items.AddObject(value2, customIndex100);

So when I will use
Code: Pascal  [Select][+][-]
  1. cb1.ItemIndex
it will return as following:
25
100

I've tried with objects, but no luck (it not returning an ID).

Thanks.
Title: Re: Populate combobox with values and custom indexes
Post by: egsuh on June 21, 2021, 07:12:13 am

Following example works.  You cannot customize indexex of items because they are TStrings property.

Code: Pascal  [Select][+][-]
  1. procedure TForm1.FormCreate(Sender: TObject);
  2. begin
  3.    combobox1.items.clear;
  4.    Combobox1.AddItem('Item A', TObject(12));
  5.    Combobox1.AddItem('Item B', TObject(25));
  6.    Combobox1.AddItem('Item C', TObject(33));
  7. end;
  8.  
  9. procedure TForm1.ComboBox1Change(Sender: TObject);
  10. var
  11.   Index: Integer;
  12.   s: string;
  13. begin
  14.   Index := ComboBox1.ItemIndex;
  15.   if Index <> -1 then begin
  16.     s := IntTostr(Integer(ComboBox1.Items.Objects[Index]));
  17.     ShowMessage(s)
  18.   end
  19.   else
  20.     ShowMessage('Nothing Selected');
  21. end;
  22.  
Title: Re: Populate combobox with values and custom indexes
Post by: noszone on June 21, 2021, 07:24:25 am
Incredible, this is exactly what I looked for, thanks.
Title: Re: Populate combobox with values and custom indexes
Post by: wp on June 21, 2021, 11:20:14 am
Code: Pascal  [Select][+][-]
  1.     s := IntTostr(Integer(ComboBox1.Items.Objects[Index]));
  2.  
Be careful, this code will crash in a 64-bit application where pointers (Combobox.Items.Objects[]) and integers have different size. Use PtrUInt or PtrInt rather than integer which are integer types having the same size as a pointer in any OS:

Code: Pascal  [Select][+][-]
  1.     s := IntTostr(PtrUInt(ComboBox1.Items.Objects[Index]));
  2.  
Title: Re: Populate combobox with values and custom indexes
Post by: egsuh on June 21, 2021, 11:28:16 am
Quote
Use PtrUInt or PtrInt rather than integer

Oh yes. This is really important information. I experienced some problem in similar occasion. Thank you very much.
Title: Re: Populate combobox with values and custom indexes
Post by: noszone on June 21, 2021, 01:35:27 pm
Such a pro tip, always learning something new :D.
TinyPortal © 2005-2018