Can I save an entry in the Item.Object property of a ListBox?

I have an entry that I would like to keep for each item added to the list. Do I need to record a class instead?

TServerRec = record ID: integer; DisplayName: string; Address: string; Port: integer; end; procedure TMainForm.PopuplateServers; var server: TServerRec; begin for server in FServerList do begin lbServers.AddObject(server.DisplayName, server); end; end; 
+4
source share
3 answers

No, but you can keep a pointer to this entry with a few types. But then you get into the dynamic allocation of pointers, which can be a bit of a headache. Why not make TServerRec an object?

+5
source

try declaring a structure like this

 type PServerRec = ^TServerRec; TServerRec = record ID: integer; DisplayName: string[255]; Address: string[255]; Port: integer; end; //now filling your list of objects procedure TForm1.Button1Click(Sender: TObject); const Max=10; var FServerList : Array [1..Max] of PServerRec; server : PServerRec; i : Integer; begin for i := 1 to Max do begin new(server); server^.DisplayName:='Server '+IntToStr(i); FServerList[i]:=server; end; for server in FServerList do begin lbServers.Items.AddObject(server.DisplayName, TObject(server)); end; end; //now to retrieve the info procedure TForm1.lbServersDblClick(Sender: TObject); var server : TServerRec; begin server:=PServerRec(lbServers.Items.Objects[lbServers.ItemIndex])^; ShowMessage(server.DisplayName); end; 

Remember to call the dispose function to free the memory of each allocated object.

+5
source

Been there, done it. I solved a similar problem by deriving a new class from the TListbox class, which included a dynamic array of records that I wanted to bind. You will need to override several TListbox methods to synchronize the dynamic array with the items from the list, but it has several advantages. For example, a dynamic recording array does not need to allocate or de-allocate memory. You just need to set the length of the array to the number of elements in your list. ( SetLength ) You do not access records through pointers, but through an index. You can simply copy entries from one place to another in the list to reorder them.
Disadvantage? This is a lot of functionality that needs to be redefined, and it’s not easy for you to check for errors in your code, since it should work at runtime and development time. Also keep in mind that you are using records, not classes. If you use classes instead, you still need to free every element of the array. But the recordings are much less complicated.

0
source

All Articles