如何通过TreeView迭代

时间:2012-05-31 22:32:26

标签: c# asp.net

我有像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

如果我检查了[CheckBox] 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);
   }
}

1 个答案:

答案 0 :(得分:0)

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

或者如果你想要父节点本身,从first-level-parent到root-parent,包括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.