从 SQL Server 数据库填充 TreeView

问题描述:

我想从 SQL 数据库填充 TreeView.

I want to populate a TreeView from SQL database.

我有一个包含 NODE_NAME 和 PARENT_NODE 列的表,子节点应该基于 PARENT_NODE 创建.

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

如何在 vb.net 中执行此操作?

How can I do this in vb.net?

有了你的 DataTable,你可以试试下面这个方法.如果它没有找到父节点,它会添加它."Find" 函数返回一个节点数组,但在这种情况下,假设没有或总是找到一个节点:

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

您可以通过枚举 DataTable 中的行来使用它:

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()