Delphi TreeView添加子节点

2024-12-27 20:50:47
推荐回答(1个)
回答1:

unit Unit1;

interface

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

type
TForm1 = class(TForm)
TreeView1: TTreeView;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
SelectedNode:TTreeNode;
implementation

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
var
node:array[1..6] of TTreeNode;
begin
node[1] := TreeView1.Items.AddChild(nil,'父节点1');
node[2] := TreeView1.Items.AddChild(node[1],'子节点11');
node[3] := TreeView1.Items.AddChild(node[1],'子节点12');
node[4] := TreeView1.Items.AddChild(nil,'父节点2');
node[5] := TreeView1.Items.AddChild(node[4],'子节点21');
node[6] := TreeView1.Items.AddChild(node[4],'子节点22');
end;

procedure TForm1.Button1Click(Sender: TObject);
var
node: TTreeNode;
str1,str2:string;
begin
SelectedNode:=TreeView1.Selected;
if SelectedNode.HasChildren then
begin
str1:= SelectedNode.Text;
str2:= copy(SelectedNode.GetLastChild.Text,
Length(SelectedNode.GetLastChild.Text),1);
str2:=inttostr(strtoint(str2)+1);
node := TreeView1.Items.AddChild(SelectedNode,str1+str2);
end else
node:=TreeView1.Items.AddChild(SelectedNode,SelectedNode.Text+'1');
end;

end.

接分

补 删除
procedure TForm1.Button2Click(Sender: TObject);
begin
SelectedNode:=TreeView1.Selected;
SelectedNode.Delete;
end;