unit TreeNodesAddObject;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls;

// BeginExample: TreeNodesAddObject
// Method: ComCtrls.TTreeNodes.AddObject
// Property: ComCtrls.TTreeNodes.Count
// Property: ComCtrls.TTreeNode.Data
// Property: ComCtrls.TTreeNode.AbsoluteIndex
// Property: ComCtrls.TCustomTreeView.Selected
// Routine: System.New

// BeginCode
{
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.
}
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;

// EndCode
// EndExample: TreeNodesAddObject
end.
