Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach cannot operate on a method group

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

I get the error: Foreach cannot operate on a method group. Did you intend to invoke the 'method group'?

like image 917
petko_stankoski Avatar asked Oct 25 '11 13:10

petko_stankoski


3 Answers

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

foreach (TreeNode tn in treeNode.Nodes)

should be

foreach (TreeNode tn in treeNode.Nodes())
like image 182
Nikola Mitev Avatar answered Oct 26 '22 05:10

Nikola Mitev


Assuming you're using the packaged TreeView control, shouldn't it be ChildNodes?:

foreach (TreeNode node in treeNode.ChildNodes) ...
like image 22
James Johnson Avatar answered Oct 26 '22 06:10

James Johnson


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

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

e.g. using for loop

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);
  }
}
like image 1
Damith Avatar answered Oct 26 '22 05:10

Damith