delphi TreeView 從資料庫新增節點的四種方法
方法一:delphi中遞迴演算法構建treeView
過程:
通過讀取資料庫中table1的資料,來構建一顆樹。table1有兩個欄位:ID,preID,即當前結點標誌和父結點標誌。所以整個樹的表示為父母表示法。本遞迴演算法不難寫,但是要注意:程式內部的變數都應使用區域性變數!比如當Query是外部變數(函式外定義或者直接通過控制元件拖拽得來)時就會得到錯誤的結果。程式碼如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, ComCtrls, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
tree: TTreeView;
Query1: TADOQuery;
procedure Button1Click(Sender: TObject);
procedure CreateTree;
private
{ Private declarations }
public
{ Public declarations }
end;
PTNodeInfo=^TNodeInfo;
TNodeInfo=record
id,preId:string;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.CreateTree;
procedure CreateTree(Pre:string;preNode:TTreeNode);
var
pInfo:PTNodeInfo;
node:TTreeNode;
sql:string;
Query:TADOQUery;
begin
Query:=TADOQuery.Create(nil);
Query.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:/實驗/遞迴父母表示/新建 Microsoft Office Access 應用程式.mdb;Persist Security Info=False';
sql:= Format('select * from table1 where preId=%s', [QuotedStr(pre)]);
Query.Close;
Query.SQL.Clear;
Query.SQL.Add(sql);
Query.Open;
Query.First;
while not Query.Eof do
begin
new(pInfo);
pInfo.id:=Query.Fields[0].AsString;
pInfo.preId:=Query.Fields[1].AsString;
node:=tree.Items.AddChild(preNode,pInfo.id);
node.Data:=pInfo;
CreateTree(pInfo.id,node);
Query.Next;
end;
Query.Close;
Query.Free;
end;
begin
createTree('000',nil);
tree.FullExpand;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
createtree;
end;
end.
createTree函式也可以這麼寫:
procedure TForm1.CreateTree;
var
p:pTNodeInfo;
procedure CreateTree(Pre:PTNodeInfo;preNode:TTreeNode);
var
pInfo:pTNodeInfo;
node:TTreeNode;
sql:string;
Query:TADOQuery;
begin
Query:=TADOQuery.Create(nil);
Query.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:/實驗/遞迴父母表示/新建 Microsoft Office Access 應用程式.mdb;Persist Security Info=False';
sql:= 'select * from table1';
Query.Close;
Query.SQL.Clear;
Query.SQL.Add(sql);
Query.Open;
Query.First;
while not Query.Eof do
begin
new(pInfo);
pInfo.id:=Query.Fields[0].AsString;
pInfo.preId:=Query.Fields[1].AsString;
if pInfo.preId=pre.id then
begin
node:=tree.Items.AddChild(preNode,pInfo.id);
node.Data:=pInfo;
CreateTree(pInfo,node);
end;
Query.Next;
end;
end;
begin
new(p);
p.id:='000';
createTree(p,nil);
tree.FullExpand;
end;
方法二://資料採用ADOQuery讀取,並將資料暫存在一個動態陣列中,樹形列表控制元件為TreeView。
procedure TForm1.LoadTreeInfo;
type
TInfo = record
ID, //程式碼
Name, //名稱
SuperID //上級程式碼
: string;
//附加欄位隨需新增
end;
var
sql: string;
i, nCount: Integer;
arrInfo: array of TInfo;
NewNode: TTreeNode;
//載入一個節點
procedure InitOneNode(ANode: TTreeNode; AId: string);
var
k: Integer;
begin
for k := 0 to length(arrInfo) - 1 do
if arrInfo[k].SuperID = AId then
begin
NewNode := TreeView1.Items.AddChild(ANode, arrInfo[k].Name);
InitOneNode(NewNode, arrInfo[k].ID);
end;
end;
begin
TreeView1.Items.BeginUpdate;
TreeView1.Items.Clear;
sql := 'select ID, Name, SuperID from DictionaryTable order by ID';
ADOQuery1.Close;
ADOQuery1.SQL.Text := sql;
ADOQuery1.Open;
nCount := ADOQuery1.RecordCount;
if nCount > 0 then
begin
SetLength(arrInfo, nCount);
for i := 0 to nCount - 1 do
with arrInfo[i] do
begin
ID := Trim(ADOQuery1.FieldByName('ID').AsString);
Name := Trim(ADOQuery1.FieldByName('Name').AsString);
SuperID := Trim(ADOQuery1.FieldByName('SuperID').AsString); //無沒有此欄位,可根據上下級編碼規則賦值
ADOQuery1.Next;
end;
end;
ADOQuery1.Close;
if nCount > 0 then
begin
InitOneNode(nil, ''); //假設頂級程式碼為空白
TreeView1.FullExpand;
TreeView1.Items.EndUpdate;
end;
end;
方法三: 此方法是第一種方法的變種,凡是有已經新增節點的,刪除。
在資料庫中建一張表,包含:NodeName,NodeId,ParentId 3個欄位,具體什麼含義,一看就知了。
過程如下:
procedure TFRM_channel.formtreenode(parentid:string;TreeView1: TTreeView;parentnode:TTreeNode;ADOQuery1:TADOQuery);
var
i:integer;
treenode:TTreeNode;
begin
i:=0;
ADOQuery1.First;
while not ADOQuery1.Eof do
begin
if ADOQuery1.FieldByName('ParentId').AsString=parentid then
begin
treenode:=TreeView1.Items.AddChild(parentnode,ADOQuery1.fieldbyname('NodeName').AsString);
formtreenode(ADOQuery1.fieldbyname('NodeId').AsString ,TreeView1,treenode,ADOQuery1);
end;
inc(i);
ADOQuery1.First;
ADOQuery1.MoveBy(i);
end;
end;
在呼叫如下,如在窗體的create事件中:
procedure TFRM_channel.FormCreate(Sender: TObject);
var
TreeNode1:TTreeNode;
i:integer;
nodename:string;
nodeid:string;
parentid:string;
cmdstr:string;
begin
//初始化樹形節點
ADOQuery1.ConnectionString:=mypublic.datastr;
cmdstr:='select * from ChanTreeNode order by ParentId ,NodeId asc';
ADOQuery1.Close;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add(cmdstr);
ADOQuery1.Open;
TreeNode1:=nil;
formtreenode('000',TreeView1,TreeNode1,ADOQuery1);
end;
方法四:用一個排序的TStringList列表,通過排序列表採用二分查詢的快速效能,就能夠很快地查詢到當前要新增節點的父節點,從而插入到 TreeView樹的正確位置。
根據資料表的內容生成TreeView樹狀結構,通常的做法就是從頂級開始,然後逐項遞迴查詢遍歷生成。這種方法在實現上容易做到,也很容易想到,但是效率比較低,因為資料庫的檢索(SQL語句需要解釋執行,而且是對資料庫檔案進行操作)還是比較耗時的,尤其是樹的層次較多,節點較多的情況。這裡我要介紹的方法是以空間換取時間,只進行一次資料庫檢索,提取出全部資料,然後一次生成TreeView樹狀結構。通過SQL語句,讓返回的記錄按照父節點ID、節點ID進行排序,這樣保證每次當前要新增的節點記錄的父節點都已經新增到了TreeView樹中,剩下的工作就是如何在TreeView樹中找到父節點。這裡我採用了一個排序的TStringList列表,通過排序列表採用二分查詢的快速效能,就能夠很快地查詢到當前要新增節點的父節點,從而插入到 TreeView樹的正確位置。
原始碼如下(假定資料表名稱為FTree,欄位有ID, ParentID, Name):
procedure MakeTree(Query: TQuery; TreeView: TTreeView);
var
List: TStringList;
Node: TTreeNode;
Index: Integer;
begin
TreeView.Items.BeginUpdate;
try
TreeView.Items.Clear;
List := TStringList.Create;
try
List.Sorted := True;
while not Query.Eof do
begin
if Query.FieldByName('ParentID').AsInteger = 0 then { ParentID=0,頂層節點 }
Node := TreeView.Items.AddChild(nil, Query.FieldByName('Name').AsString)
else
begin
Index := List.IndexOf(Query.FieldByName('ParentID').AsString);
Node := TreeView.Items.AddChild(TTreeNode(List.Objects[Index]),
Query.FieldByName('Name').AsString);
end;
List.AddObject(Query.FieldByName('ID').AsString, Node);
Query.Next;
end;
finally
List.Free;
end;
finally
TreeView.Items.EndUpdate;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
T: DWORD;
begin
T := GetTickCount;
Query1.SQL.Text := 'SELECT * FROM FTree ORDER BY ParentID, ID';
Query1.Open;
MakeTree(Query1, TreeView1);
Label1.Caption := Format('MakeTree所用時間: %d ms', [GetTickCount - T]);
end;
==============================================================================
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, ADODB;
type
PTNode=^TNode;
TNode=record
id:string;
fID,nID:string;
hasCreate:boolean;
fChild:PTNode;
nSibling:PTNode;
end;
type
TArr=array of TNode;
type
TTree=class(TObject)
root,cur:PTNode;
constructor create; overload;
constructor create(var arr:TArr); overload;
function FindNode(s:string;p:PTNode):boolean;
end;
type
TForm1 = class(TForm)
Button1: TButton;
conn: TADOConnection;
Query: TADOQuery;
Memo1: TMemo;
procedure DisPlayFChild(p:PTNode);
procedure LoadData(var arr:Tarr);
function GetNode(var arr:Tarr;s:string):PTNode;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.displayFChild(p:PTnode);
begin
if p.fChild<>nil then begin memo1.Lines.Add(p.fchild.id); end;
end;
function TTree.FindNode(s:string;p:PTNode):boolean;
var
pn:PTNode;
begin
result:=false;
if p.id=s then
begin
result:=true;
cur:=p;
exit;
end;
pn:=p.fChild;
while ((pn<>nil)and (FindNode(s,pn)=false)) do
begin
pn:=pn.nSibling;
end;
end;
function TForm1.GetNode(var arr:Tarr;s:string):PTNode;
var
i,n:integer;
begin
result:=nil;
n:=Length(arr);
for i:=0 to n-1 do
begin
if (arr[i].id=s) then
begin result:[email protected][i]; exit; end;
end;
end;
procedure TForm1.LoadData(var arr:TArr); //load data from database
var
i:integer;
begin
Query.Close;
Query.SQL.Clear;
Query.SQL.Add('select * from table2');
Query.Open;
Query.First;
i:=Query.RecordCount;
setLength(arr,i);
i:=0;
while not Query.Eof do
begin
arr[i].id:=Query.Fields[0].AsString;
arr[i].fID:=Query.Fields[1].AsString;
arr[i].nID:=Query.Fields[2].AsString;
arr[i].hasCreate:=false;
i:=i+1;
Query.Next;
end;
Query.Close;
end;
constructor TTree.create;
begin
root:=nil;
end;
constructor TTree.create(var arr:TArr); //create a tree from arr
var
i,j,n:integer;
p:PTNode;
begin
i:=0;
n:=Length(arr);
while i<n do
begin
j:=0;
while j<n do
begin
if (arr[j].id='root') and (arr[j].hasCreate=false) then
begin
new(root);
root:[email protected][j];
root.fChild:=nil;
root.nSibling:=nil;
cur:=root;
i:=i+1;
arr[j].hasCreate:=true;
end;
if arr[j].hasCreate=true then
begin
if arr[j].fid<>'none' then
begin
p:=Form1.GetNode(arr,arr[j].fID);
if p.hasCreate=false then
begin
arr[j].fChild:=p;
p.hascreate:=true;
p.fchild:=nil;
p.nsibling:=nil;
i:=i+1;
end;
end;
if arr[j].nid<>'none' then
begin
p:=Form1.GetNode(arr,arr[j].nID);
if p.hascreate=false then
begin
arr[j].nSibling:=p;
p.hascreate:=true;
p.fchild:=nil;
p.nsibling:=nil;
i:=i+1;
end;
end;
end;
j:=j+1;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
arr:TArr;
aTree:TTree;
begin
LoadData(arr);
aTree:=TTree.create(arr);
memo1.Lines.Add(atree.root.fchild.fchild.nsibling.nsibling.id); //test
aTree.Free;
end;
end.
---------------------
作者:甜而不膩
來源:CSDN
原文:https://blog.csdn.net/ingener/article/details/78363562
版權宣告:本文為博主原創文章,轉載請附上博文連結!