type //在类中先定义好
Groupifo = ^TMyRec;
TMyRec = record
Name: string;
DepartID: string;
end;
//初始化部门树 你可以先添加两层,在窗体创建时调用这个函数
procedure InitDeptTreeView(TreeView:TTreeView
;
var FirstItem,Temp:TtreeNode;
DeparInf:Groupifo;
Begin
TreeView.Items.Clear ;
FirstItem:=TreeView.Items.Add(nil,'单位信息');
Query1.Close;
Query1.Sql.Clear;
Query1.Sql.Add('SELECT * FROM 表名 WHERE 父单位编号='0');
Query1.Open;
Query1.First;
while Not Query1.Eof Do
begin
New(DeparInf);
if Not Query1.FindField(单位编号).IsNull Then
DeparInf^.DepartID:=Query1.FieldValues [单位编号];
if Not Query1.FindField(单位名称).IsNull Then
DeparInf^.Name:=Query1.FieldValues [单位名称];
Temp:=TreeView.Items.AddChildObject(FirstItem,DeparInf^.Name,DeparInf);
FindChoseBoyItem(Temp,TreeView);
Query1.Next ;
End;
Query1.Close ;
End;
////在当前选中部门上创建子部门
procedure FindChoseBoyItem(ChoseItem:TTreeNode;TreeView:TTreeView);
var
DeparInf:Groupifo;
Begin
Query.Close;
Query.Sql.Clear;
Query.Sql.Add('SELECT * FROM 表名 WHERE 父单位编号=Groupifo(ChoseItem.Data)^.DepartID);
Query.Open;
Query.First;
If Query.RecordCount<>0 Then
Begin
While Not Query.Eof do
Begin
New(DeparInf);
if Not Query1.FindField(单位编号).IsNull Then
DeparInf^.DepartID:=Query1.FieldValues [单位编号];
if Not Query1.FindField(单位名称).IsNull Then
DeparInf^.Name:=Query1.FieldValues [单位名称];
TreeView.Items.AddChildObject(ChoseItem,DeparInf^.Name,DeparInf);
Query.Next ;
End;
End
Else
Query.Close ;
End;
在TreeView1的onChange事件中写
procedure TForm1.TreeView1Change(Sender: TObject;Node: TTreeNode);
Var
Item: TTreeNode;
Begin
If Node.Level<>0 Then
Begin
DeptID1:=Groupifo(NodeData)^.DepartID;
If Node.SelectedIndex<>1 Then
Begin
Item:=Node.getFirstChild;
While Item<>Nil Do
Begin
FindChoseBoyItem(Item,TreeView1);
Item := Item.getnextsibling;
End;
End;
End;
End;