Ok, assuming that the Project node is the root node of the TreeView, here's how I'd do it. (Note: this is mostly pseudocode, just to show the logic.)
The thing about treeviews (or any hierarchical data structure) is that they can be processed most easily (IMHO) using recursion. So, I'm going to make a sub that 1)process the node passed to it and 2)checks that node for children and if they are found, passes the first child node to the sub itself.
I'm not sure if I'd just update the existing data, or clear out the table each time and insert the treeview node data "fresh" on each save. I'd probably go with clearing out the table before each save, so:
Now that the table is empty, save the Project node to the database.
Here's the Sub to save the node data:
Code:
Private Sub SaveTreeviewData(ByVal StartNode As TreeNode)
If StartNode.Nodes.Count > 0 Then
For Each n As TreeNode In StartNode.Nodes
SaveTreeviewData(n)
Next
Else
'Save tree node data to database
'First, get the IDNum of the current node' parent
Dim ParentNodeID As String
If StartNode.Parent IsNot Nothing Then
'node has a parent node, so get that ID
'assuming that the node's ID is stored in the .Tag property
ParentNodeID = StartNode.Parent.Tag
Else
'no parent node, so this is a root node
ParentNodeID = ""
End If
'Use ParentNodeID to populate the ParentNode field
'Insert Into TreeNodeTable (IDNum, ParentNode, Field1, Field2, ...) VALUES (@IDNum, @ParentNode, @Field1, @Field2, ...)
End If
End Sub
To call this sub, do this:
Code:
For Each n As TreeNode In TreeView1.Nodes
SaveTreeviewData(n)
Next
So, this code goes through each root node and passes it to SaveTreeviewData. That sub checks if the node passed in has children. If it does, the sub loops through the children, calling SaveTreeviewData and passing each child node.
Using recursion like this, it doesn't matter how deep the nodes are nested.
To get the data out of the database and back into the treeview, use something similar. First, get all root nodes (i.e., all records in the database that have a blank value for ParentNode). Using a recursive procedure call, you can loop through all the root records and fill out the nodes in the treeview.
I'll leave it to you to write the code to read the database and populate the treeview (hint: it's very similar to the code to save the treeview data).
If you run into any problems or questions, please post here and we'll help.
I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson
Arrrr, mateys! Ye needs ta be preparin' yerselves fer
Talk Like a Pirate Day!