asp.netvb.nettreeviewchild-nodes

VB. NET Add multiple ChildNodes in a Treeview


I have many records in a database and I need to populate my treeview dynamically like this: Below is just an example of what I need:

TreeView1.Nodes(a).ChildNodes.Add(New TreeNode("ChildNode " & b))
TreeView1.Nodes(a).ChildNodes(b).ChildNodes.Add(New TreeNode("ChildNode 2 lvl " & b))

I'm getting the records from a MySQL Db and I need to know how can I add multilevel ChildNodes into a loop For ... Next etc...

Do you have any suggestion or idea???


Solution

  • if you want to work with various levels of Treenodes you can use Find function

    Dim TempNode As TreeNode = TreeView1.Nodes.Find("Node where I want to add SubNode", True).FirstOrDefault

    TempNode.Nodes.Add("SubNode", "SubNode")

    This way you can add SubNode to any Node you pick.

    .Find("key",True)finds treenodes with following key and .FirstOrDefault picks first. Finally you just add new SubNode to Tempnode.

    You considered you are getting it dynamically and from MySql. It may cause error like "Action beeing preformed on this control is being called from the wrong thread. Marshal to the correct thread using Contol.Invoke or Control.BeginInvoke to perform this action." Simply change TempNode.Nodes.Add("SubNode", "SubNode") to TreeView1.Invoke(Sub() TempNode.Nodes.Add("SubNode", "SubNode"))

    EXAMPLE:

    Dim comm As String = "SELECT * FROM YourTableName"
    Dim SqlCmnd as SqlCommand = New SqlCommand(comm, YourMySqlConnection)
    Dim READER As SqlDataReader
    READER = SqlCmnd.ExecuteReader
    While READER.Read
        Dim NewNode As TreeNode = New TreeNode(READER.Item("origCategoryID"))
        TreeView1.Nodes.Add(NewNode)
        NewNode.Nodes.Add(READER.Item("categoryOrderID"))
    End While
    READER.Close()
    

    EXAMPLE 2:

    output database

    While READER.Read
    If TreeView1.Nodes.Find(READER.Item("OrigCatOrderID"), True).Length > 0 Then
    Dim NewNode As TreeNode = TreeView1.Nodes.Find(READER.Item("OrigCatOrderID"), True).FirstOrDefault
    NewNode.Nodes.Add(READER.Item("CatOrderID"), READER.Item("CatOrderID"))
    Else
    TreeView1.Nodes.Add(READER.Item("OrigCatOrderID"), READER.Item("OrigCatOrderID"))
    TreeView1.Nodes(READER.Item("OrigCatOrderID")).Nodes.Add(READER.Item("CatOrderID"), READER.Item("CatOrderID"))
    End While