TreeView 树形显示的问题 table1 id name pid 1 root 001 2 child 001001 3 child2 001002 4 root2 002
发布网友
发布时间:2022-05-25 01:14
我来回答
共1个回答
热心网友
时间:2023-11-20 22:58
给你个例子
unit PublicTree;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ImgList,DB, Menus;
type
TFrameTree = class(TFrame)
tvTree: TTreeView;
ImageList1: TImageList;
procere tvTreeExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
procere tvTreeChange(Sender: TObject; Node: TTreeNode);
private
PDataSet:TDataSet;
PID,PName,PParentId:TField;
public
procere TreeInit(DataSet:TDataSet;ID,Name,ParentId:TField);
function TreeAddItem(Parent: TTreeNode;Resort: Boolean): TTreeNode;
procere TreeDeleteItem(node:TTreeNode);
function TreeFindItem(ID:string): TTreeNode;
end;
implementation
uses PubFun;
function TFrameTree.TreeAddItem(Parent: TTreeNode;Resort: Boolean): TTreeNode;
var
ParentNo: string;
node: TTreeNode;
begin
if (parent=nil) or (pos('_',parent.text)<1) then
ParentNo:=''
else
ParentNo:=GetCommaStr(Parent.Text,1,'_');
Pdataset.DisableControls;
Pdataset.First;
while not pdataset.Eof do
begin
if PParentId.AsString= ParentNo then
begin
node:=tvTree.Items.AddChild(parent,pid.asstring+'_'+pname.asstring);
node.HasChildren:=true;
node.ImageIndex:=0;
node.SelectedIndex:=1;
end;
pdataset.Next;
end;
Pdataset.EnableControls;
if Resort and (parent<>nil) then parent.alphasort;
if(Parent<>nil)and(Parent.Count<=0)then Parent.HasChildren:=false;
if tvTree.Selected=nil then
begin
node:=treefinditem(pid.AsString);
tvTree.Selected:=node;
end
else
Pdataset.Locate(pid.FieldName,GetCommaStr(tvTree.Selected.text,1,'_'),[]);
end;
procere TFrameTree.TreeInit(DataSet:TDataSet;ID,Name,ParentId:TField);
begin
PDataset:=Dataset;
PID:=ID;
PName:=name;
PParentID:=parentID;
end;
procere TFrameTree.tvTreeExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
begin
if node.Count<=0 then
treeadditem(node,true);
end;
procere TFrameTree.tvTreeChange(Sender: TObject; Node: TTreeNode);
begin
if pdataset.State in [dsInsert,dsEdit] then pDataset.Post;
if node<>nil then
if pos('_',node.Text)>0 then
if not Pdataset.Locate(PID.FieldName,GetCommaStr(node.text,1,'_'),[]) then
raise exception.Create('记录未找到!');
end;
procere TFrameTree.TreeDeleteItem(node: TTreeNode);
begin
tvTree.Items.Delete(node);
end;
function TFrameTree.TreeFindItem(ID:string): TTreeNode;
var
node:TTreeNode;
begin
Node:= tvTree.Items.GetFirstNode;
if (Node<> nil) and (GetCommaStr(Node.text,1,'_') <> ID) then
repeat
Node := Node.GetNext;
until (Node = nil) or (GetCommaStr(Node.text,1,'_')= ID);
Result := Node;
end;
end.
调用生成
cdsTree.Open;
FrameTree1.TreeInit(cdsTree,cdsTree.FieldByName(CodeField),cdsTree.FieldByName(NameField),cdsTree.FieldByName(ParentField));
node:=FrameTree1.tvTree.Items.Add(nil,TopText);
node.HasChildren:=true;
node.Expand(false);
另外,站长团上有产品团购,便宜有保证追问呵呵,谢谢了,问题已经解决了,用的是xml树型显示的