unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, ComCtrls, Grids, DBGrids, StdCtrls, Menus;
type
TForm1 = class(TForm)
Button1: TButton;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
TreeView1: TTreeView;
ADOQuery1: TADOQuery;
PopupMenu1: TPopupMenu;
Add: TMenuItem;
Edit: TMenuItem;
Delete: TMenuItem;
refresh: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure AddClick(Sender: TObject);
private
{ Private declarations }
public
function GetParentNode(P_Id: string): TTreeNode;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TInfo = record
P_Name: string[32];
ID: string[32];
P_Id: string[32];
end;
PInfo = ^TInfo;
procedure TForm1.FormCreate(Sender: TObject);
begin
with ADOQuery1 do
begin
close;
sql.Text:= 'select * from treeTable order by P_ID,ID';
open;
end;
end;
function TForm1.GetParentNode(P_Id: string): TTreeNode;
var
i: integer;
begin
Result:= nil;
for i:= 0 to TreeView1.Items.Count -1 do
begin
if PInfo(TreeView1.Items.Data).P_Id = P_Id then
Result:= TreeView1.Items;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
aTreeNode: TTreeNode;
Info: PInfo; //用此变量去封装树节点的data属性
begin
New(info); //开指针内存
TreeView1.Items.BeginUpdate;//防止树频繁刷新
TreeView1.Items.Clear; //初始化
try
with ADOQuery1 do
begin
first;
while not Eof do
begin
Info.P_Id:= FieldByName('P_ID').AsString;
Info.Id:= FieldByName('ID').AsString;
Info.P_Name:= FieldByName('P_Name').AsString;
aTreeNode:= GetParentNode(FieldByName('P_Id').AsString);
if aTreeNode = nil then
begin
TreeView1.Items.AddNode(nil,nil,info.P_Name,info,naAddChild);
end
else
begin
TreeView1.Items.AddNode(nil,aTreeNode,info.P_Name,info,naAddChild);
end;
next;
end;
end;
finally
dispose(info);//释放指针内存
end;
TreeView1.Items.EndUpdate; //beginUpdate - endUpdate 配对使用
TreeView1.FullExpand;//展开整个树
end;
procedure TForm1.AddClick(Sender: TObject);
var
Info: PInfo; //用此变量去封装树节点的data属性
begin
new(info);
try
if TreeView1.Selected <> nil then
begin
info.P_Name:= 'new node';
info.P_Id:= pinfo(TreeView1.Selected.Data).ID;
//info.Id:= ...这由你自己的子节点编码规则生成相应的编码
TreeView1.Items.AddNode(nil,TreeView1.Selected,info.P_Name,info,naAddChild);
//保存到数据库的部分你自己完成
end;
finally
dispose(info);
end;
end;
end.
//我改了不行 数据如下:
ID P_ID P_name all_name
52 0 贵州省 贵州省
5227 52 贵阳市 贵州省贵阳市
522729 5227 惠水县 贵州省贵阳市惠水县
522728 5227 罗甸县 贵州省贵阳市罗甸县
52272901 522729 好花乡 贵州省贵阳市惠水县好花乡
52272902 522729 长田乡 贵州省贵阳市惠水县长田乡
显示 贵州省
-贵阳市
-惠水县
-好花乡
-长田乡
-罗甸县