Create a catalog database
Create Table Catalog (ID N(10), Parent N(10), Name C(50))
The ID field must be an unique number with start from 1 to 9999999999. Parent is the number pointing to the parent node (Previous level). In this program, 0 (zero) is the root node (first node) of the tree.
The ID field must be an unique number with start from 1 to 9999999999. Parent is the number pointing to the parent node (Previous level). In this program, 0 (zero) is the root node (first node) of the tree.
Create a form
Add a TreeView control into a form. Name it as tvwCatalog. This is what I usually do. I use txtSomething to indicate the object is a text box. tvw is stand for TreeView. Although it is not quite necessary, but with a good practice is always a good idea. In the Form1.Init, add Do Load_Catalog with this, 0
Create a recursive program (Load_Catalog)
Here is the code of the Load_Catalog.Prg
LPARAMETERS pTree, pNode
Private xQ, xParent, xID, xName, xCheck
IF pTree.Nodes.Count = 0
pTree.Nodes.Add (,, 'C0', 'Root')
pTree.Nodes.Item('C0').Expanded = .T.
pTree.Nodes.Item('C0').Checked = .T.
ENDIF
***** SYS(2015) returns a temporary file name
xQ = SYS(2015)
Select * from Catalog ;
WHERE Parent = pNode ;
ORDER BY Name ;
INTO CURSOR &xQ
***** If this parent has child node
IF RECCOUNT() > 0
SCAN
xParent = 'C' + ALLTRIM(STR(&xQ..Parent)) xID = 'C' + ALLTRIM(STR(&xQ..ID))
xName = ALLTRIM(&xQ..Name)
pTree.Nodes.Add (xParent, 4, xID, xName) DO Load_Catalog WITH pTree, &xQ..ID
ENDSCANENDIF
Select &xQ
USE
Test the code
Since the Catalog database has no record. You should only see the "Root" in the tree. Later I added an "ADD" button. Here is the code:
PRIVATE xName, xID, xParent, xName
xName = ALLTRIM(INPUTBOX('Please enter a name', ;
'Add New Catalog', ''))
IF NOT EMPTY(xName)
SELECT MAX(ID + 1) as NewID FROM Catalog INTO CURSOR Q1
IF RECCOUNT() = 0
xID = 1
ELSE
xID = IIF(RECCOUNT() = 0, 1, Q1.NewID)
ENDIF
xParent = VAL(SUBSTR(thisform.tvwCatalog.SelectedItem.Key, 2))
INSERT INTO Catalog (ID, Parent, Name) ;
VALUES (xID, xParent, xName)
thisform.tvwCatalog.Init
ENDIF
Since the Catalog database has no record. You should only see the "Root" in the tree. Later I added an "ADD" button. Here is the code:
PRIVATE xName, xID, xParent, xName
xName = ALLTRIM(INPUTBOX('Please enter a name', ;
'Add New Catalog', ''))
IF NOT EMPTY(xName)
SELECT MAX(ID + 1) as NewID FROM Catalog INTO CURSOR Q1
IF RECCOUNT() = 0
xID = 1
ELSE
xID = IIF(RECCOUNT() = 0, 1, Q1.NewID)
ENDIF
xParent = VAL(SUBSTR(thisform.tvwCatalog.SelectedItem.Key, 2))
INSERT INTO Catalog (ID, Parent, Name) ;
VALUES (xID, xParent, xName)
thisform.tvwCatalog.Init
ENDIF
No comments:
Post a Comment