TTreeView 连接数据库,树状展示人员信息管理效果不错

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    DataSource1: TDataSource;
    ClientDataSet1: TClientDataSet;
    DBGrid1: TDBGrid;
    TreeView1: TTreeView;
    Splitter1: TSplitter;
    procedure FormCreate(Sender: TObject);
    procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
  node: TTreeNode;
  List: TStringList;
  s: string;
begin
  {country.xml 是 Delphi 的数据示范文件, 也可以用 country.cds}
  ClientDataSet1.FileName := 'c:\temp\country.xml';
  ClientDataSet1.Active := True;
  DataSource1.DataSet := ClientDataSet1;
  DBGrid1.DataSource := DataSource1;
  {上面四行是让数据构件互相挂接, 也可以在设计时设定}

  {建立 List}
  List := TStringList.Create;
  List.Sorted := True;           {指定排序}
  List.Duplicates := dupIgnore;  {避免重复}

  {把数据加入到 TreeView}
  for i := 0 to ClientDataSet1.FieldDefs.Count - 1 do
  begin
    node := TreeView1.Items.Add(nil, ClientDataSet1.FieldDefs[i].Name); {字段名}

    {为避免数据重复, 先把数据给 List}
    List.Clear;
    ClientDataSet1.First;
    while not ClientDataSet1.Eof do
    begin
      List.Add(ClientDataSet1.Fields[i].value);
      ClientDataSet1.Next;
    end;
    {把 List 中的数据加入到 TreeView}
    for s in List do TreeView1.Items.AddChild(node, s);
  end;

  List.Free;
end;

procedure TForm1.TreeView1Change(Sender: TObject; Node: TTreeNode);
begin
  if Node.Parent <> nil then
  begin
    {下面的 Filter 其实就是 SQL 查询语句, 如果用其他数据库替换就是}
    ClientDataSet1.Filter := Node.Parent.Text + '=''' + Node.Text + '''';
    ClientDataSet1.Filtered := True;
  end else ClientDataSet1.Filtered := False; {选字段名时取消过虑}
end;

end.



附数据库样本:

posted @ 2016-04-01 10:56  南国之恋  阅读(340)  评论(0编辑  收藏  举报