简体   繁体   中英

How to Iterate through TreeView

I have TreeView Web Control like

1
  1.1
2
  2.1
     2.1.1
          2.1.1.1
          2.1.1.2
3
  3.1 
     3.1.1

If i have checked [CheckBox] 2.1.1.2 node , how can i get the result like 2,2.1,2.1.1 and 2.1.1.2
I have tried to use this http://msdn.microsoft.com/en-us/library/wwc698z7.aspx example but it doesnt give me required out put. Any Help or instructions how to achieve the required out put will be much appreciated.

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

Or if you want the parent nodes themselves, from first-level-parent to root-parent, including 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM