【问题标题】:List all child nodes of a parent node in a treeview control in Visual C#在 Visual C# 中的树视图控件中列出父节点的所有子节点
【发布时间】:2023-03-14 14:15:01
【问题描述】:

我有一个树视图控件,它包含一个父节点和来自该父节点的几个子节点。有没有办法从主父节点获取所有子节点的数组或列表?即从 treeview.nodes[0] 或第一个父节点获取所有节点。

【问题讨论】:

    标签: c# treeview


    【解决方案1】:
    public IEnumerable<TreeNode> GetChildren(TreeNode Parent)
    {
        return Parent.Nodes.Cast<TreeNode>().Concat(
               Parent.Nodes.Cast<TreeNode>().SelectMany(GetChildren));
    }
    

    【讨论】:

      【解决方案2】:

      您可以像这样递归地添加到列表中:

      public void AddChildren(List<TreeNode> Nodes, TreeNode Node)
      {
          foreach (TreeNode thisNode in Node.Nodes)
          {
              Nodes.Add(thisNode);
              AddChildren(Nodes, thisNode);
          }
      }
      

      然后调用这个程序传入根节点:

      List<TreeNode> Nodes = new List<TreeNode>();
      AddChildren(Nodes, treeView1.Nodes[0]);
      

      【讨论】:

      • 感谢您提供此代码!我不得不更改 foreach 以使其工作,如下所示: foreach (TreeNode thisNode in Node.ChildNodes)
      • @Svein 那是因为您使用的是 WPF,但此代码适用于 WinForms。 WinForms 中没有 ChildNodes。
      【解决方案3】:

      你可以做这样的事情..来获取树视图中的所有节点..

       private void PrintRecursive(TreeNode treeNode)
       {
           // Print the node.
            System.Diagnostics.Debug.WriteLine(treeNode.Text);
            MessageBox.Show(treeNode.Text);
            // Print each node recursively.
             foreach (TreeNode tn in treeNode.Nodes)
             {
                 PrintRecursive(tn);
              }
       }
      
         // Call the procedure using the TreeView.
       private void CallRecursive(TreeView treeView)
       {
            // Print each node recursively.
              TreeNodeCollection nodes = treeView.Nodes;
               foreach (TreeNode n in nodes)
               {
                   PrintRecursive(n);
                }
         }
      

      请你看看这个链接。

      http://msdn.microsoft.com/en-us/library/wwc698z7.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 2014-12-19
        • 1970-01-01
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多