Board index » delphi » strange question in treeview

strange question in treeview

 I can't set the right value to the treeview.item[i].data,

the programm is below:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ComCtrls;
type
  pmyrec=^myrec;
  myrec=record
    x:string;
    y:string;
    z:string;
end;
type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    Button1: TButton;
    Label1: TLabel;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
var i:integer;
    lv_myprec:pmyrec;
begin
  new(lv_myprec);

  for i:=0 to 3 do begin
    lv_myprec^.x:=inttostr(i);
    lv_myprec^.y:=inttostr(i);
    lv_myprec^.z:=inttostr(i);
    treeview1.items.AddObject(nil,'item'+inttostr(i),lv_myprec);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
 Label1.Caption := PMyRec(TreeView1.Selected.Data)^.x + ' ' +
                  PMyRec(TreeView1.Selected.Data)^.y+'
'+PMyRec(TreeView1.Selected.Data)^.y;

end;
end.

When I click button1,Label1 always display the value '3 3 3'.why ? can
someone help me to debug??

 

Re:strange question in treeview


You should create more than one lv_myprec. Move the "new(lv_myprec);"
statement inside the "for i:=0 to 3 do begin" block, and create a new
lv_myprec for each item in the tree. Now all nodes in the tree points to the
same object.

Thor-Willy

Other Threads