vb.net 从 SQL Server 数据库填充 TreeView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21043768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:24:52  来源:igfitidea点击:

Populate TreeView from SQL Server database

vb.netwinformstreeview

提问by SellaKumar

I want to populate a TreeView from SQL database.

我想从 SQL 数据库填充 TreeView。

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

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

How can I do this in vb.net?

我怎样才能在 vb.net 中做到这一点?

enter image description here

在此处输入图片说明

回答by LarsTech

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:

使用您的数据表,您可以在下面尝试此方法。如果它没有找到父节点,它会添加它。"Find" 函数返回一个节点数组,但在这种情况下,假设始终找不到节点或一个节点:

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:

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

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