Foreach cannot work in a group of methods

private void PrintRecursive(TreeNode treeNode) { foreach (TreeNode tn in treeNode.Nodes) { PrintRecursive(tn); } } 

I get an error: Foreach cannot work in a group of methods. Did you intend to call a "group of methods"?

+8
foreach treeview
source share
3 answers

Assuming you are using a TreeView batch control, there should be no ChildNodes ?:

 foreach (TreeNode node in treeNode.ChildNodes) ... 
+6
source share

The problem is that Nodes is a method, but you use it as a property :) So, this line of code

 foreach (TreeNode tn in treeNode.Nodes) 

it should be

 foreach (TreeNode tn in treeNode.Nodes()) 
+11
source share

TreeView.Nodes provides a collection of TreeNode objects that represents the root nodes in a TreeView control.

To access the child nodes of the root node, use the ChildNodes node property.

eg. use for cycle

 void PrintRecursive(TreeNode node) { for(int i=0; i <node.ChildNodes.Count; i++) { PrintRecursive(node.ChildNodes[i]); } } 

or using foreach

 void PrintRecursive(TreeNode node) { foreach(TreeNode node in node.ChildNodes) { PrintRecursive(node); } } 
+1
source share

All Articles