[2003] How to populate a treeview?
I have a table with the structure COMPANY(company_ID, company_name, parent_company_ID). In case, parent_company_ID is the Parent ID of the company (all parent and sub-company are stored in COMPANY table). I want to show the structure of company on the treeview (may be a lot of node level). I have ran these codes:
Code:
Dim rd As SqlClient.SqlDataReader = get_recordset("SELECT * FROM company ORDER BY company_ID")
While rd.Read
If rd("parent_company_ID") = 0 Then 'root level
Dim nd As System.Windows.Forms.TreeNode
nd = tv.Nodes.Add(rd("company_name"))
nd.Tag = rd("company_ID")
Else
For Each nod As TreeNode In tv.Nodes
If nod.Tag.ToString = rd("parent_company_ID").ToString Then
Dim nd As System.Windows.Forms.TreeNode = nod.Nodes.Add(rd("company_name"))
nd.Tag = rd("company_ID")
Exit For
End If
Next nod
End If
End While
But I 've got a treeview with two level (with company belongs to more than 3 level, they can not appearance on the treeview)
Does anyone help me to populate the treeview on this case?
Regards,
Hai
Re: [2003] How to populate a treeview?
All trees are recursive structures. Whenever you want to populate a TreeView you should think recursion as a first option:
vb.net Code:
Private Sub LoadChildNodes(ByVal parentID As Integer, _
ByVal nodes As TreeNodeCollection, _
ByVal table As DataTable)
Dim filterExpression As String
If parentID = -1 Then
'Get all the rows with no parent.
filterExpression = "ParentID IS Null"
Else
'Get all child rows of the specified parent.
filterExpression = "ParentID = " & parentID
End If
Dim childNode As TreeNode
For Each childRow As DataRow In table.Select(filterExpression)
'Add the new node.
childNode = nodes.Add(CStr(childRow("Name")))
'Load all children of the new node.
Me.LoadChildNodes(CInt(childRow("ID")), _
childNode.Nodes, _
table)
Next childRow
End Sub
You would start the ball rolling like so:
vb.net Code:
Me.LoadChildNodes(-1, Me.TreeView1.Nodes, myDataTable)
Obviously you will have to change the variable and column names to match those in your own app.
Re: [2003] How to populate a treeview?
Thank you jmcilhinney,
It's done