Now most of the methods are recursive, but this kind of operation will frequently go to select database, reduce the execution efficiency, slightly change some, the effect will be much better, here is a method, that is, a one-time select out all the data, and then according to ParentID sort, added to the TreeView, Before adding, go through the TreeView, look for his previous node, traverse the TreeView can be faster than select data, see Code: Data table structure, top parentid value I use 1, you can also use other values, but to ensure that the top ParentID value is minimal, The deeper the level,
procedureTuioperate.filltree (rzchecktree:trzchecktree);varFindq:tadoquery; Node:ttreenode; //This method is based on the ID field value of the record, looking for the parent node on the Rzchecktree functionFindparentnode (Id:integer): Ttreenode; varI:integer; beginResult:=Nil; forI: =0 toRzCheckTree.Items.Count-1 Do begin //Compare the data value of node and the ID value of the record ifInteger (Rzchecktree.items[i]. DATA) = ID Then beginResult:=Rzchecktree.items[i]; break; End; End; End;beginFINDQ:= Tadoquery.Create(Nil); Findq. Connection:= Controler. Dataconnect.connection;//Here's the connection point to your data connection TryRzCheckTree.Items.BeginUpdate; RzCheckTree.Items.Clear; //Select All records and sort by parentid to ensure that the top-level node is added first, and the parent node is always found when the subordinate record is addedFindq. Sql. Text: ='SELECT * FROM [Catalog] ORDER by Parentid,id'; Findq. Open; while notFindq. Eof Do begin //if it is the top level, add it directly to the Rzchecktree ifFindq. Fieldbyname ('ParentID'). Asinteger =-1 Then //Save the ID value in node's data to find theRzCheckTree.Items.AddObject (Nil, FINDQ. Fieldbyname ('CatalogName'). Asstring,pointer (FINDQ. Fieldbyname ('ID'). Asinteger))Else begin //Find ancestor nodeNode: = Findparentnode (FINDQ. Fieldbyname ('ParentID'). Asinteger); ifNode <>Nil ThenRzCheckTree.Items.AddChildObject (NODE,FINDQ. Fieldbyname ('CatalogName'). Asstring,pointer (FINDQ. Fieldbyname ('ID'). Asinteger)); End; Findq. Next; End; finallyFINDQ. Free; RzCheckTree.Items.EndUpdate; End;End;
Generate Rzchecktree based on database structure