1 unit TV_Add_Remove_U1; 2 3 { 4 This demo was written by Andre .v.d. Merwe and marked public domain. 5 Quickly converted to Lazarus and FPC by Tom Lisjac <vlx@users.sourceforge.net> 6 7 The original source and an *excellent* tutorial on the TTreeview 8 component can be found here: 9 http://users.iafrica.com/d/da/dart/Delphi/TTreeView/TreeView.html 10 } 11 12 interface 13 14 {$mode objfpc} {$H+} 15 16 uses 17 SysUtils, LResources, Classes, LCLProc, Graphics, Controls, Forms, Dialogs, 18 StdCtrls, ComCtrls, Buttons; 19 20 type 21 TForm1 = class(TForm) 22 tv_eg1: TTreeView; 23 but_Add: TButton; 24 but_Remove: TButton; 25 procedure but_AddClick(Sender: TObject); 26 procedure but_RemoveClick(Sender: TObject); 27 private 28 public 29 constructor Create(TheOwner: TComponent); override; 30 end; 31 32 var 33 Form1: TForm1; 34 35 implementation 36 37 procedure TForm1.but_AddClick(Sender: TObject); 38 var 39 sText : ansistring; 40 begin 41 {If nothing is selected} 42 if( tv_eg1.Selected = nil ) then 43 begin 44 {Does a root node already exist?} 45 if( tv_eg1.Items.Count = 0 ) then 46 begin 47 {Add the root node} 48 with tv_eg1.Items.AddFirst( nil, 'Root' ) do 49 begin 50 Selected := true; 51 debugln('tv_eg1.Selected=',DbgS(tv_eg1.Selected)); 52 end; 53 end 54 else begin 55 {There is a root, so user must first select a node} 56 //MessageBeep( -1 ); 57 ShowMessage( 'Select a parent node' ); 58 Exit; 59 end; 60 end 61 else begin 62 {Get a name for the new node} 63 sText := 'New node'; 64 InputQuery( 'New Node', 'Caption ?', sText ); 65 66 {Add the node as a child of the selected node} 67 with tv_eg1.Items.AddChild( tv_eg1.Selected, sText ) do 68 begin 69 MakeVisible; 70 end; 71 end; 72 end; 73 74 75 76 procedure TForm1.but_RemoveClick(Sender: TObject); 77 begin 78 {Make sure somthing is selected, before trying to 79 delete it} 80 if( tv_eg1.Selected = nil ) then 81 begin 82 //MessageBeep( -1 ); 83 ShowMessage( 'Nothing selected' ); 84 Exit; 85 end; 86 87 {Dont allow user to delete the root node} 88 if( tv_eg1.Selected.Level = 0 ) then 89 begin 90 //MessageBeep( -1 ); 91 ShowMessage( 'Cant delete the root node' ); 92 Exit; 93 end; 94 95 96 {Delete the node} 97 tv_eg1.Selected.Delete; 98 end; 99 100 constructor TForm1.Create(TheOwner: TComponent); 101 var 102 RootNode: TTreeNode; 103 begin 104 inherited Create(TheOwner); 105 RootNode:=tv_eg1.Items.AddFirst(nil,'Root'); 106 tv_eg1.Items.AddChild(RootNode,'Node1'); 107 tv_eg1.Items.AddChild(RootNode,'Node2'); 108 tv_eg1.Items.AddChild(RootNode,'Node3'); 109 RootNode.Expanded:=true; 110 end; 111 112 {$R *.lfm} 113 114 end. 115