Populate TreeView from SQL Server database

2019-07-23 22:26发布

问题:

I want to populate a TreeView from SQL database.

I have a table with NODE_NAME AND PARENT_NODE columns and the child nodes should b created based on the PARENT_NODE.

How can I do this in vb.net?

回答1:

With your DataTable, you can try this method below. If it doesn't find the parent node, it adds it. The "Find" function returns an array of nodes, but in this case, it's assumed none or one node is always found:

Private Sub AddNode(parentNode As String, nodeText As String)
  Dim node As New List(Of TreeNode)
  node.AddRange(TreeView1.Nodes.Find(parentNode, True))
  If Not node.Any Then
    node.Add(TreeView1.Nodes.Add(parentNode, parentNode))
  End If
  node(0).Nodes.Add(nodeText, nodeText)
End Sub

You would use it by enumerating through the rows in your DataTable:

For Each dr As DataRow In dt.Rows
  AddNode(dr("ParentNode").ToString, dr("NodeName").ToString)
Next
TreeView1.ExpandAll()