|
-
Nov 11th, 2011, 08:42 AM
#1
Thread Starter
Frenzied Member
[RESOLVED] Best way to load treeview from database.
What is the best to load a treeview from a database where it goes 4 deep
Code:
Parent
child
child
grandchild
grandchild
child
child
grandchild
great grandhcild
grandchild
How would that look in a database? and then how would you load the tree. I can load everything up to the grandchild, but as soon as I load the great grandchild I start having issues. So I am thinking it is the way they are in the database.
Anybody have any examples they can share?
-
Nov 11th, 2011, 09:43 AM
#2
Re: Best way to load treeview from database.
It depends on the data. It might be stored in four different tables with each record having a foreign key from the table above or it might all be stored in one table with each record containing the ID of its parent. In the second case, loading the data might look like this:
vb.net Code:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Dim table As New DataTable 'Populate table here. AddNodes(Me.TreeView1.Nodes, table, Nothing) End Sub Private Sub AddNodes(nodes As TreeNodeCollection, table As DataTable, parentID As Integer?) Dim filter = If(parentID.HasValue, "ParentID = " & parentID, "ParentID IS NULL") Dim rows = table.Select(filter) For Each row In rows Dim id = row.Field(Of Integer)("ID") Dim node = nodes.Add(id.ToString(), row.Field(Of String)("Name")) 'Make a recursive call to add child nodes to this node. AddNodes(node.Nodes, table, id) Next End Sub
-
Nov 11th, 2011, 08:17 PM
#3
Thread Starter
Frenzied Member
Re: Best way to load treeview from database.
The latter is what I have. But it doesn't work when I have grand children. I mean it works but I get repeats of ones that don't belong there. I just wanted to make sure I was doing it correctly.
-
Nov 12th, 2011, 12:32 AM
#4
Re: Best way to load treeview from database.
Either you code is wrong or your data is wrong. We haven't seen either so we can't really help.
-
Nov 12th, 2011, 10:38 AM
#5
Thread Starter
Frenzied Member
Re: Best way to load treeview from database.
its not the most elegant way after seeing your sample code.
http://www.vbforums.com/showthread.php?t=662713
-
Nov 12th, 2011, 12:40 PM
#6
Thread Starter
Frenzied Member
Re: Best way to load treeview from database.
I think I got it. I converted your code to work with mine and it solved the problem. I don't have any bleed over. I knew it was the way I was loading the tree and seeing your code I seen my problem. More efficient too, lol
Thank you JM, much appreciated to lead me in the right direction.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|