Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store a record in a ListBox's Item.Object property?

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;
like image 624
fossilz Avatar asked Dec 28 '22 05:12

fossilz


2 Answers

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?

like image 73
Mason Wheeler Avatar answered Dec 31 '22 14:12

Mason Wheeler


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.

like image 39
RRUZ Avatar answered Dec 31 '22 14:12

RRUZ