Delphi TreeView - creating nodes at runtime

Can someone tell me how to do the following:

  • Create Nodes
  • Enable / disable individual nodes

I want to know how to do this at runtime, for example, in the Form OnCreate event.

+7
delphi treeview
source share
3 answers

Adding nodes:

function FindRootNode(ACaption: String; ATreeView: TTreeView): TTreeNode; var LCount: Integer; begin result := nil; LCount := 0; while (LCount < ATreeView.Items.Count) and (result = nil) do begin if (ATreeView.Items.Item[LCount].Text = ACaption) and (ATreeView.Items.Item[LCount].Parent = nil) then result := ATreeView.Items.Item[LCount]; inc(LCount); end; end; ... var LDestNode: TTreeNode; begin LDestNode := FindRootNode('category', TreeView1); if LDestNode <> nil then begin TreeView1.Items.AddChild(LDestNode, 'node1'); TreeView1.Items.AddChild(LDestNode, 'node2'); end; end; 

(see also http://msdn.microsoft.com/en-us/library/70w4awc4.aspx )

Cancel node

As far as I know, there is no way to disable TreeNode. The only thing you can do is to intercept the beforeSelect event and deselect. Not very nice.

+8
source share

@Remus, here you have a simple example of adding nodes.

Adding Node Root (Level 0)

 Var Node : TTreeNode; begin //function TTreeNodes.Add(Sibling: TTreeNode; const S: string): TTreeNode; Node:=TreeView1.Items.Add(nil,'My Root Node') ; Node.ImageIndex:=0;//now you can change any property of the node end; 

Adding a Node child (level> 0)

 //in this case we add a child node in the current selected node. Var Node : TTreeNode; begin if TreeView1.Selected= nil then exit; Node:=TreeView1.Items.AddChild(TreeView1.Selected,'My Child Node') ; Node.ImageIndex:=0;//now you can change any property of the node end; 

Adding multiple nodes

if you want to add many nodes using a loop or something else you should use BeginUpdate before making changes to the tree structure. When all changes complete the call to EndUpdate to show the changes on the screen. BeginUpdate and EndUpdate prevent excessive redrawing and speed up processing time when nodes are added, deleted or inserted.

 Var Node : TTreeNode; i : Integer; begin TreeView1.Items.BeginUpdate; try for i:=1 to 100 do begin Node:=TreeView1.Items.Add(nil,'My Root Node '+IntToStr(i)) ; Node.ImageIndex:=0; end; finally TreeView1.Items.EndUpdate; end; end; 

About disabling node, there is no such property.

+14
source share

You can disable the selection in the OnChanging event handler. This is a TTreeView event.

 procedure TForm.OnChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); begin AllowChange := CheckSomePropertiesOfNode(Node); end; 
+2
source share

All Articles