给你一个源代码,我做的,单击二级结点时,在treeview中动态添加三级结点,然后把选中的结点
内容在edit中显示 并在单击父结点时展开子结点:
unit untsd;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables, ComCtrls, StdCtrls, ExtCtrls;
type
Tfrmsd = class(TForm)
Query1: TQuery;
GroupBox1: TGroupBox;
TreeView1: TTreeView;
edtsd: TEdit;
btnok: TButton;
Bevel1: TBevel;
procedure FormCreate(Sender: TObject);
procedure TreeView1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnokClick(Sender: TObject);
procedure TreeView1KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmsd: Tfrmsd;
implementation
uses getin;
{$R *.DFM}
procedure Tfrmsd.FormCreate(Sender: TObject);
var treenode:ttreenode;
begin
treeview1.items.clear;
treenode:=treeview1.items.add(nil,'各行政区划一览表');
query1.Close ;
query1.sql.Clear;
query1.sql.add('select dvs,cod from admd where cod like ''__0000'' order by dvs');
query1.open;
with TreeView1.Items do
begin
while not query1.eof do
begin
addchild(treenode,query1.fieldbyname('dvs').asstring);
query1.next;
end;
end;
end;
procedure Tfrmsd.TreeView1Click(Sender: TObject);
var selnode,parentnode:ttreenode;
begin
selnode:=treeview1.selected;
parentnode:=treeview1.selected.Parent ;
if not treeview1.selected.expanded then
begin
//若为根结点
if parentnode=nil then exit;
//若为二级结点且
if parentnode.parent=nil then
begin
if (not selnode.haschildren) then // 此时还没有添加三级结点
begin
query1.close;
query1.sql.clear;
query1.SQL.add('select * from admd where dvs like
dvs order by dvs');
query1.parambyname('pdvs').asstring:=''+treeview1.selected.text+'%'+'';
query1.open;
query1.next; //从第2个记录开始写,因为查找出的第一个记录为xx省
while not query1.eof do
begin
treeview1.items.addchild(selnode,query1.fieldbyname('dvs').asstring);
query1.next;
end;
edtsd.text:=selnode.text;
selnode.Expand (true);
end
else // 此时已经添加三级结点
edtsd.text:=selnode.text;
end
else
if (not selnode.haschildren) then edtsd.text:=selnode.text //若为三级结点
end
else
if parentnode<>nil then edtsd.text:=selnode.text;
end;
procedure Tfrmsd.FormClose(Sender: TObject; var Action: TCloseAction);
begin
edtsd.Text :='';
treeview1.FullCollapse;
end;
procedure Tfrmsd.btnokClick(Sender: TObject);
begin
if edtsd.Text <>'' then regist.edtsd.Text :=edtsd.Text;
close;
end;
procedure Tfrmsd.TreeView1KeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then edtsd.text:=treeview1.selected.text;
end;
end.