用AddObject,将ListBox的每一个item和一定的数据相关联。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
ListBox1: TListBox;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
type
PListItem = ^TMyListItem;
TMyListItem = record
s1,s2: string; //或是其它类型的数据。
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
ListItemPtr: PListItem;
begin
new(ListItemPtr);
ListItemPtr.s1 := 's1';
ListItemPtr.s2 := 's2';
listbox1.Items.AddObject('k',TObject(ListItemPtr));
end;
procedure TForm1.ListBox1Click(Sender: TObject);
var ListItemPtr: PListItem;
begin
ListItemPtr:= PListItem(ListBox1.items.Objects[ListBox1.ItemIndex]);
label1.Caption:=ListItemPtr.s1+':'+ListItemPtr.s2;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
i:integer;
begin
for i := 0 to ListBox1.items.count -1 do
freemem(PListItem(listbox1.Items.Objects));
end;
end.