Many systems have a table structure similar to the following (table1):
IDName ParentID
-------------------------------------------------- -------
001 Electronics0
002 Metal 0
003 Capacitor Electronics001
004 Resistance Electronics001
005 Non-ferrous metals002
And everyone is accustomed to using tree (TreeView) to display, so that the classification of the entire table can be well displayed. However, if the amount of data is large, the generation of the tree will be slower, especially when using recursion to implement it, the number of database accesses will be many (depending on the number of layers), and the effect will be more obvious when used in three layers. Here is a good way to generate a tree structure.
This algorithm only accesses the database once. The specific implementation is as follows:
1. Get all the data from the database at one time and sort it according to the ParentID field, so as to ensure that the parent node of each piece of data is in front of it.
2. Take out the first piece of data and draw it into the tree. When adding it to the tree, first find the parent node of this data. If there is no parent node, use this record directly as the first-level node of the tree.
3. If there is still data, take it out and perform step 2 until there is no data.
Program implementation:
This program will use a TStringList variable of stlID to store the ID value of each node in the corresponding tree, and use the FindParent function to find the parent node.
function FindParent(ID:String):TTreeNode;
var
i:Integer;
begin
result:=nil;
for i:=TreeView1.Items.Count-1 downto 0 do
if stlID.Strings[i]=ID then
begin
result:=TreeView1.Items[i];
break;
end;
end;
// Spanning tree
PRocedure CreateTree;
var
tmpNode:TTreeNode;
begin
Query1.close;
Query1.SQL.Text:='select * from table1 order by ParentID';
Query1.Open;
Query1.First;
while not Query1.Eof do
begin
tmpNode:=TreeView1.Items.AddChild(FindParent(Query1.FieldByName('ParentID').AsString),Query1.FieldByName('Name').AsString);
stlID.Add(Query1.FieldByName('ID').AsString);//Record ID
Query1.Next;
end;
end;