TreeNodesAddObject (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example requires three buttons, four TEdits, two labels, and a populated TreeView. The following code defines a record type of TMyRec and a record pointer type of PMyRec.

Code

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Edit1: TEdit;
    TreeView1: TTreeView;
    Label2: TLabel;
    Label3: TLabel;
    Button3: TButton;
    Edit4: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  type
  PMyRec = ^TMyRec;
  TMyRec = record
    FName: string;
    LName: string;
  end;


var
  Form1: TForm1;

implementation

{$R *.dfm}

{
Assuming these types are used, the following code adds a
node to TreeView1 as the last sibling of the selected node.
A TMyRec record is associated with the added item. The FName
and LName fields are obtained from edit boxes Edit1 and
Edit2.
procedure TForm1.Button1Click(Sender: TObject);
var
  MyRecPtr: PMyRec;
  TreeViewIndex: LongInt;
begin
  New(MyRecPtr);
  MyRecPtr^.FName := Edit1.Text;
  MyRecPtr^.LName := Edit2.Text;
  with TreeView1 do
  begin
    TreeViewIndex := Selected.AbsoluteIndex;
    if Items.Count = 0 then
      Items.AddObject(nil, 'Item' + IntToStr(TreeViewIndex), MyRecPtr)
    else if (TreeViewIndex < Items.Count) and (TreeViewIndex >= 0) then
      Items.AddObject(Items[TreeViewIndex], 'Item' + IntToStr(TreeViewIndex), MyRecPtr);
  end;
end;
{
After an item containing a TMyRec record has been added, the
following code retrieves the FName and LName values
associated with the item and displays the values in a label.
procedure TForm1.Button2Click(Sender: TObject);
begin
  if (TreeView1.Selected.Data <> nil) then { Query only works on new nodes. }
    Edit3.Text := PMyRec(TreeView1.Selected.Data)^.FName + ' ' +
                  PMyRec(TreeView1.Selected.Data)^.LName;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
  Edit4.Text := IntToStr(TreeView1.Selected.AbsoluteIndex);
end;

Uses

Personal tools
Assistance