Add node under a spacific node, VB.net treeview

taz8020
taz8020 used Ask the Experts™
on
Hi I want to be able to add a node, under a spacific node. may be by path or index?

I have a table in a typed dataset in a win app, and need to loop through each row. I have an ID field and a ParentID field. I want it to be able to have infanate child nodes. So the only way I can see of doing this is when adding a node look to see if there are child nodes then add them. |Just not sure how to go about doing this.

This is what I have so far:

For i = 0 To Me.DataSet.sections.Rows.Count - 1
If Me.ActinicDataSet.Catalog_section.Rows(i).Item("ParentID") = 0 Then
Me.TreeView1.Nodes.Add(Me.DataSet.sections.Rows(i).Item("SectionText"))
'Need to add child nodes here.
End If
Next
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
The Add-function returns the created node as a result. You can then use that node as a parent to set the subsequent nodes.
Dim childNode As TreeNode = New TreeNode("Text for new childnode")
TreeNode node = Me.TreeView1.Nodes.Add(Me.DataSet.sections.Rows(i).Item("SectionText"))
node.Add( childNode )
 

Author

Commented:
Hi djjaries, thanks for that. Is there a way if datasouce has children add child node. and if that childnode has children add thoses nodes and so on.
I have an ID field and a ParentID field in the same data table.

eg
-id
--id
----id
-----id
-id
-----id
Commented:
Of course,
for each row in your datasource,
if the parentId is null, add the node under root.
If the parentid does not equal null, find the node with that value and add the new node as a child of the found node.
For this method, you will get the best results if you sort your datasource on (ParentId, Id). Otherwise you will have  to run multiple times through the rows to ensure that you get every node.
See attached code
 

dim id as string
dim parentid as string

For i = 0 To Me.DataSet.sections.Rows.Count - 1
  parentid = Me.ActinicDataSet.Catalog_section.Rows(i).Item("ParentID").ToString()
  id = Me.ActinicDataSet.Catalog_section.Rows(i).Item("ID").ToString() 

  If parentid = "0" Then
    Me.TreeView1.Nodes.Add(Me.DataSet.sections.Rows(i).Item(id, "SectionText"))

  Else
    If Me.TreeView1.Nodes.ContainsKey(parentid) Then
      Me.TreeView1.Nodes[parentid].Nodes.Add(id, "childsectionText")
    End If
  End If
Next

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial