如何循环访问树视图

本文关键字:访问 视图 循环 何循环 | 更新日期: 2023-09-27 18:35:52

我有像 TreeView Web Control 这样的

1
  1.1
2
  2.1
     2.1.1
          2.1.1.1
          2.1.1.2
3
  3.1 
     3.1.1

如果我选中了 [复选框] 2.1.1.2 节点,我如何获得 2,2.1,2.1.1 和 2.1.1.2 这样的结果
我试图使用这个 http://msdn.microsoft.com/en-us/library/wwc698z7.aspx 的例子,但它没有给我所需的输出。任何帮助或说明如何实现所需的输出将不胜感激。

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.ChildNodes)
   {
      PrintRecursive(tn);
   }
}
// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
   // Print each node recursively.
   TreeNodeCollection nodes = treeView.CheckedNodes; // Modified to get the Checked Nodes
   foreach (TreeNode n in nodes)
   {
      PrintRecursive(n);
   }
}

如何循环访问树视图

var texts = new List<string> { treeNode.Text };
while (treeNode.Parent != null)
{
    texts.Add(treeNode.Parent);
    treeNode = treeNode.Parent;
}
//Reverse to get the required Layout of the Tree
texts.Reverse(); 
var result = string.Join("'r'n", texts);

或者,如果你想要父节点本身,从一级父节点到根父节点,包括 self:

var parents = new List<TreeNode> { treeNode };
while (treeNode.Parent != null)
{
    parents.Add(treeNode.Parent);
    treeNode = treeNode.Parent;
}
// Now parents contains the results. Do whatever you want with it.