I have a Record that I would like to store for each Item that add to a Listbox. Would I need to make the record a class instead to accomplish this?
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;
No, but you could store a pointer to this record with a bit of typecasting. But then you're getting into dynamic record pointer allocation, which can be a bit of a headache. Why not make TServerRec into an object?
try declarating you 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;
don't forget to call the dispose
function to free the memory of each object allocated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With