Save and Load a TreeView to SQL Database

C

cjinsocal581

Hi all, I am struggling with the following:

Environement:
VB.NET 2005
TreeView Control
SQL Database

I need to be able to save a TreeView's nodes into a SQL database and
then be able to call them from the Table back into the TreeView when
the app starts up. (If the table is empty, then just exit the sub)

The structure of the TreeView will be something like this.

ParentNode
--childNode1
--childNode2
--childNode3
ParentNode2
--childNode1
--childNode2
ParentNode3
--childNode1

The Treeview will only have one level of children nodes for each parent
node.

So my question is, how should I format my table to save this data and
are they any code samples to show me how to do this?

Any assistance would be greatly appreciated.
 
A

Aboulfazl Hadi

Hi
Suppose you have a table named MyTable with the following columns:
ID
Title
ParentID

add two button and a treeview , store id in treeNode's tag . ( it is
better to use inheritance for this kind of storing data):

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
SaveTree(TreeView1.Nodes)
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim table As DataTable
' populate table with data


LoadTree(table)
End Sub
Private Sub SaveTree(ByVal nodes As TreeNodeCollection)
For Each node As TreeNode In nodes
SaveNode(node)
SaveTree(node.Nodes)
Next
End Sub

Private Sub SaveNode(ByVal Node As TreeNode)
AddRowToMyTable(CInt(Node.Tag), Node.Text,
CInt(Node.Parent.Tag))
End Sub

Private Sub LoadTree(ByVal table As DataTable)
For Each row As DataRow In table.Rows
AddNode(row("ID"), row("Title"), row("ParentID"))
Next
End Sub

Private Sub AddNode(ByVal id As Integer, ByVal title As String,
ByVal parentID As Integer)
Dim newNode As New TreeNode
newNode.Text = title
newNode.Tag = id
If parentID = -1 Then
TreeView1.Nodes.Add(newNode)
Else
Dim parentNode As TreeNode = FindParent(parentID)
parentNode.Nodes.Add(newNode)
End If

End Sub


I hope this helps
A.Hadi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top