unitUnit1;interface
usesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, DB, ADODB;typePNodeInfoEx=^TNodeInfoEx;
TNodeInfoEx=Packed Record
NodeID : Integer;
ParentID : Integer;
NodeType : Integer;
ChnNodeTitle : String;
ImageIndex: SmallInt;
SelectedIndex: SmallInt;end;
TForm1= class(TForm)
tv1: TTreeView;
btn1: TButton;
qry1: TADOQuery;procedurebtn1Click(Sender: TObject);procedureFormDestroy(Sender: TObject);private
{Private declarations}
functionStaticBuildTree(TreeView:TTreeView ):Boolean;functionAddTreeItem(TreeView:TTreeView; AddNodeInfo:PNodeInfoEx):TTreeNode;functionFindTreeItem(TreeView:TTreeView; CurNodeID:integer): TTreeNode;public
{Public declarations}
end;varForm1: TForm1;implementation
{$R *.dfm}
functionTForm1.StaticBuildTree(TreeView:TTreeView ):Boolean;varAddNodeInfo : PNodeInfoEx;beginResult :=False;
qry1.LoadFromFile('c:/AdminixTree.xml');//这里以XML文件做为数据源
Treeview.Items.BeginUpdate;//记住:在进行批量添加数据时要使用BeginUpdate,来暂时关闭由于添加数据而触发的某些事件(如OnChange事件等)
Treeview.Items.Clear;//清空Treeviewtry
try
if qry1.RecordCount >0 then
beginqry1.First;while Not qry1.Eof do
beginNew(AddNodeInfo) ;//生成结构体
AddNodeInfo^.NodeID := qry1.FieldByName('NODE_ID').AsInteger;
AddNodeInfo^.ParentID := qry1.FieldByName('PARENT_ID').AsInteger;
AddNodeInfo^.NodeType := qry1.FieldByName('NodeType').AsInteger;
AddNodeInfo^.ChnNodeTitle := qry1.FieldByName('ChnNodeTitle').AsString;
AddNodeInfo^.ImageIndex := qry1.FieldByName('ImageIndex').AsInteger;
AddNodeInfo^.SelectedIndex := qry1.FieldByName('SelectedIndex').AsInteger;
AddTreeItem(Treeview,AddNodeInfo);//把结构体的指针存到Treeview中
qry1.Next;end;end;exceptApplication.MessageBox('生成树结点失败',MB_ICONSTOP+MB_OK);raise;//向上级抛异常end;
qry1.Close;
Result :=True;finallyTreeview.Items.EndUpdate;end;end;//在加入结点时,应先判断加入的是父结点还是子结点,判断的依据是在已存在的树结点中是否存在该结点的ParentIDfunctionTForm1.AddTreeItem(TreeView:TTreeView; AddNodeInfo:PNodeInfoEx):TTreeNode;varParentNode: TTreeNode;beginParentNode :=FindTreeItem(Treeview,AddNodeInfo^.ParentID);
If ParentNode<> nil thenResult :=Treeview.Items.AddChildObject(ParentNode, Trim(AddNodeInfo.ChnNodeTitle), Pointer(AddNodeInfo))elseResult :=Treeview.Items.AddObject(ParentNode, Trim(AddNodeInfo.ChnNodeTitle), Pointer(AddNodeInfo));if Result<>nil then
beginResult.ImageIndex :=AddNodeInfo.ImageIndex;
Result.SelectedIndex :=AddNodeInfo.SelectedIndex;end;end;//这里是判断是否存在其父结点functionTForm1.FindTreeItem(TreeView:TTreeView; CurNodeID:integer): TTreeNode;vari : Integer;beginResult := nil;for i := 0 to Treeview.Items.Count-1 do
begin
if CurNodeID=PNodeInfoEx(Treeview.Items[i].Data)^.NodeID then
beginResult :=Treeview.Items[i];
Exit;end;end;end;//生成树结构procedureTForm1.btn1Click(Sender: TObject);beginStaticBuildTree (tv1)end;//在窗体释放时一定要把树结点中的结构体指针给释放掉,对于在Dispose时为什么要进行强制转型后释放,以前有专门的讲解,在此不在累述procedureTForm1.FormDestroy(Sender: TObject);vari : Integer;begin
for i := 0 to tv1.Items.Count-1 do
beginDispose( PNodeInfoEx(tv1.Items[i].Data) )end;end;end.