学习 TTreeView [7] - Insert、Delete
学习 TTreeView [7] - Insert、Delete
涂孟超 发表于3年前
学习 TTreeView [7] - Insert、Delete
  • 发表于 3年前
  • 阅读 5
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

本例效果图:


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.

 
 
 
 
 

 

 

  
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 12
博文 2004
码字总数 14107
×
涂孟超
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: