1

我有 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);
   }
}
4

1 回答 1

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

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

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.
于 2012-05-31T22:53:16.577 回答