Many systems have a table structure similar to the following (Table1):
ID Name ParentID
-------------------------------------------------- -------
001 electronic class 0
002 metal 0
003 capacitor electronic 001
004 resistance electronic 001
005 non-ferrous metal 002
And everyone is accustomed to displaying with TreeView, so that you can display the classification of the entire table well. However, if the amount of data is more slow, it is more time to generate the tree, especially when the return is implemented, and the number of times to access the database (depending on the number of layers), the effect is more effective in the three layers. A good method is provided here to generate a tree structure.
This algorithm only accesses a database, the specific implementation is as follows:
1. All data is removed from the database in one time and sorted according to the ParentID field, which ensures that the parent node of each data is in front of it.
2. Remove the first data to the tree, first find the parent node of this data before adding to the tree. If not, this record directly as the first level node of the tree.
3, if there is data, take it out to perform step 2 until no data is available.
Program implementation:
This program will use a STLID's TSTRINGLIST variable to store the ID value of each node in the tree and use the findparent function to 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 life
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;