本例效果图:
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Grids, ExtCtrls; type TForm1 = class(TForm) TreeView1: TTreeView; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var Nodes: TTreeNodes; node: TTreeNode; begin TreeView1.Align := alLeft; Nodes := TreeView1.Items; node := Nodes.Add(nil, '一连长'); node := Nodes.AddChild(node, '一排长'); node := Nodes.AddChild(node, '一班长'); node := Nodes.AddChild(node, '战士1'); Nodes.Add(node, '战士2'); Nodes.Add(node, '战士3'); Nodes.Add(node, '战士4'); node := node.Parent; Nodes.Add(node, '二班长'); Nodes.Add(node, '三班长'); node := node.Parent; Nodes.Add(node, '二排长'); Nodes.Add(node, '三排长'); node := node.Parent; Nodes.Add(node, '二连长'); Nodes.Add(node, '三连长'); end; {初始化} procedure TForm1.Button1Click(Sender: TObject); begin TreeView1.Items.Clear; FormCreate(nil); TButton(Sender).Caption := '初始化'; end; {删除} procedure TForm1.Button2Click(Sender: TObject); var node: TTreeNode; begin if not Boolean(TreeView1.Items) then Exit; {如果 TreeView1 无内容} if TreeView1.SelectionCount = 0 then Exit; {如果无选择} node := TreeView1.Selected; node.Delete; TButton(Sender).Caption := '删除'; end; {删除它的所有下级} procedure TForm1.Button3Click(Sender: TObject); var node: TTreeNode; begin if not Boolean(TreeView1.Items) then Exit; if TreeView1.SelectionCount = 0 then Exit; node := TreeView1.Selected; if node.HasChildren then node.DeleteChildren else ShowMessage(node.Text + ' 没有下级'); TButton(Sender).Caption := '删除下级'; end; {用 TTreeNodes 删除} procedure TForm1.Button4Click(Sender: TObject); var node: TTreeNode; begin if not Boolean(TreeView1.Items) then Exit; if TreeView1.SelectionCount = 0 then Exit; node := TreeView1.Selected; TreeView1.Items.Delete(node); TButton(Sender).Caption := '用 TTreeNodes 删除'; end; {插入, 只能通过 TTreeNodes} procedure TForm1.Button5Click(Sender: TObject); var node: TTreeNode; begin if not Boolean(TreeView1.Items) then Exit; if TreeView1.SelectionCount = 0 then Exit; node := TreeView1.Selected; TreeView1.Items.Insert(node, '新成员'); TButton(Sender).Caption := '插入'; end; end.