本例效果图:


unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    Memo1: TMemo;
    Panel1: TPanel;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{初始化 TreeView1}
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);
const
  path = 'c:\temp\tree.txt';
begin
  TreeView1.SaveToFile(path);
  TButton(Sender).Caption := '保存';
end;

{从文件中载入}
procedure TForm1.Button2Click(Sender: TObject);
const
  path = 'c:\temp\tree.txt';
begin
  if FileExists(path) then TreeView1.LoadFromFile(path);
  TButton(Sender).Caption := '载入';
end;

{从流中读取}
procedure TForm1.Button3Click(Sender: TObject);
var
  stream: TStream;
begin
  stream := TMemoryStream.Create;
  try
    Memo1.Lines.SaveToStream(stream);
    stream.Position := 0;
    TreeView1.LoadFromStream(stream);
  finally
    stream.Free;
  end;
end;

end.

注意: 上面例子中的"从流中读取"部分, 对 Memo 中的数据格式有严格要求, 要求必须是树状结构;
结构中可以用"空格"和"Tab"分层.

posted on 2008-03-12 15:31  万一  阅读(6036)  评论(15编辑  收藏  举报