Add child nodes to treeview

stustarz

Well-known member
Joined
Jan 10, 2003
Messages
246
Location
Earth
Hello

I currently have the following code to retrive records from a Dataset and populate the treeview. I would like to now place child nodes under each parent, from a different dataset where the seasons are equal (youll see what i mean in the code). Im really stuck as to how to do this:

Current Code:

Populate Treeview
Dim varTVItem As TreeNode
Dim varDSRow As DataRow

tvSeasons.Nodes.Clear()
dsSeasonData = DsSeasons1
For Each varDSRow In dsSeasonData.Tables("seasons").Rows

varTVItem = New TreeNode()

With varTVItem
.Text = varDSRow.Item("Season")
End With
tvSeasons.Nodes.Add(varTVItem)
Next

Thanks in advance
 
Each Node is an object in itself, of type TreeNode. Every Node has a Nodes collection, of all its children.

So to add a child node, use myNode.Nodes.Add().
 
Hi

Thanks for the reply

The only problem im having is implementing this into the code. Would be able to tell me how to put this into the code I already have.

Thanks
 
No, because I dont know how your data is structured.

To add a child node to the one youre making,

Code:
varTVItem.Nodes.Add("blah")
 
Each time you call Add, it returns the node that was added. Using that node, you can add children easily. As divil said, your DataSet may be structured to make things easier (or even recursive), but heres a sample to show how to add 3 parent nodes. Each parent node will have 2 children.

Code:
// Add a parent node
TreeNode node = treeView1.Nodes.Add("hello 1");
// Add two children.
// This works because both children use "node" as the parent
// to add to. The "node" variable is not reset
// til farther down.
node.Nodes.Add("child 1");
node.Nodes.Add("child 2");

// Here, node is reset to be the *next*
// parent node. Its a parent because its
// added directly to the treeView1 control
node = treeView1.Nodes.Add("hello 2");
node.Nodes.Add("child 1");
node.Nodes.Add("child 2");

node = treeView1.Nodes.Add("hello 3");
node.Nodes.Add("child 1");
node.Nodes.Add("child 2");

-Nerseus
 
Back
Top