By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,526 Members | 2,189 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,526 IT Pros & Developers. It's quick & easy.

Save and Load a TreeView to SQL Database

P: n/a
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.

Mar 1 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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

Mar 1 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.