Ram
Ram

Reputation: 933

Not able to break foreach loop

I like to select the node where its text matches to some stirng values for this I wriiten one recursive method

private TreeNode GetSelectedNodes(TreeNode treeNode)
    {
        TreeNode result=new TreeNode();
        foreach (TreeNode node in treeNode.Nodes)
        {
            if (node.Text=="Child1")
            {
                result=node;
                break;
            }
            else
            if (node.Nodes.Count > 0)
            {
                this.GetSelectedNodes(node);
            }
        }
        return result;
    }

in above code one of node Text matches to "Child1" but its not returning node instead its again calling this.GetSelectedNodes(node); Please let me know what wrong with this code.

Upvotes: 0

Views: 108

Answers (2)

Mojtaba
Mojtaba

Reputation: 1240

trythis

private TreeNode GetSelectedNodes(TreeNode treeNode)
{            
    foreach (TreeNode node in treeNode.Nodes)
    {
        if (node.Text=="Child1")
        {                   
            return node;
        }
        else
        {
            if (node.Nodes.Count > 0)
            {
                var result = this.GetSelectedNodes(node);
                if(result != null)
                {
                    return result;
                }
            }
        }
    }
    return null;
}

Upvotes: 3

Dakotah Hicock
Dakotah Hicock

Reputation: 390

Try this way. You return the node once found, and returns all the way up

private TreeNode GetSelectedNodes(TreeNode treeNode)
{
    TreeNode result=new TreeNode();
    foreach (TreeNode node in treeNode.Nodes)
    {
        if (node.Text=="Child1")
        {
            result=node;
            return result;
        }
        else if (node.Nodes.Count > 0)
        {
            return this.GetSelectedNodes(node);
        }
    }
}

Upvotes: -1

Related Questions