,一个Treeview 跟DBGrid1关联的有关问题,小弟还是初学者,分也不多,只有30分,还请相助!

各位大哥,一个Treeview 跟DBGrid1关联的问题,小弟还是菜鸟,分也不多,只有30分,还请各位大哥相助!!!!
一个treeview,一个dbgrid,和ADOQuery,datasource1通过单击treeview的结点,让dbgrid显示结点相关联的的数据。  
  如树的结构如下  
  甲公司
  A部门 
  B部门  
  c部门 
  D部门 
  I部门
   
  乙公司  
  F部门 
  H部门  
   
其中有两个表:
  表一:EpDept (部门结构表)
  DpId (int) DpNa (varchar) DpTyp(varchar) DpPrId(int)
  01 甲公司 001 nill
  02 A部门 001001 01
  03 B部门 001002 01
  04 c部门 001002001 03
  05 D部门 001002001001 04
  06 乙公司 002 nill
  07 F部门 002001 06
  08 H部门 002002 06
  09 I部门 001003 02
  表二:Employee (员工信息表)
  EpId EpNa DpId
  1 张三 05
  2 李四 09
   
 
  现在我已经根据EpDept 中的DpId 、DpPrId字段生成了树型结构。我现在的问题是:
我单击 “甲公司” 节点是,需要在dbgrid中显示其甲公司下各部门的员工信息,但不要显示乙公司各部门的信息??
或者说点“B部门”时只显示其下的所属员工,而不显示其他部门的员工。。。。。。。。
急切等待中。。。。。。

------解决方案--------------------
思路是在部门树节点 TreeNode.Data 域存储部门相关信息,核心是DeptId,然后在树节点变化时,刷新员工记录。
定义部门数据结构
type
PDeptInfo=^TDeptInfo;
TDeptInfo=record
DpId: integer;
DpNa: string;
DpPrId: integer;
end;

假定部门树名称 tvDept
生成树的时候,在添加节点的时候需要稍微做一点处理:

procedure DestroyTree();
var
i: integer;
begin
tvDept.OnChange := nil;
for i:=0 to tvDept.Items.Count-1 do Dispose(PDeptInfo(tvDept.Items[i].Data));
tvDept.Items.Clear;
end;

procedure BuildDeptTree();
var
node: TTreeNode;
lpDept: PDeptInfo;
begin
DestroyTree();

添加树节点
new(lpDept);
lpDept^.DpId := ...
...
node.data := lpDept;
  
tvDept.OnChange := OnRefreshEmployee;
end;

procedure OnRefreshEmployee(Sender: TObject; Node: TTreeNode);
var
strSql: string;
begin
if tvDept.Selected <> nil then
strSql := 'select * from Employee where DpId='+IntToStr(PDeptInfo(tvDept.Selected.Data)^.DpId
else
strSql := 'select * from Employee where 1<0'; //没选中部门,则没有任何人员记录。
生成记录集
end;

最后,模块关闭的时候,记得把树销毁回收资源!
------解决方案--------------------
只是个数据查询的问题。

03 B部门 001002 01 
04 c部门 001002001 03 
05 D部门 001002001001 04 
假设现在选中的是B部门,根据DpTyp like'001002%'可以查询得到其子部门 001002001和001002001001
最终得到DpId=03,04,05,然后根据得到的这三个DpId到Employee中查询就可以到的你想要的结果了。

select * from Employee where DpId in(select DpId from EpDept where DpTyp like'001002%')