开发者

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

I have a Record that I wou开发者_StackOverflow社区ld 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.


Been there, done that. I solved a similar problem by deriving a new class from the TListbox class, which included a dynamic array of the records that I wanted to keep linked. You will need to override several of the TListbox methods to keep the dynamic array synchronized with the items witin the listbox but it has a few advantages. For example, a dynamic array of record doesn't need to allocate or de-allocate memory. You just need to set the length of the array equal to the number of items in your list. (SetLength) You're not accessing records through pointers but through an index. You can just copy records from one location to another in the list, to re-order them.
The drawback? It's a lot of functionality that needs to be overridden and it's not easy to check for bugs in your code, since it needs to work in runtime and design-time. Also be aware that you use records, not classes. If you use classes instead, then you still need to free each element in the array. But records are a lot less complex.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜