Sangram Nandkhile
Sangram Nandkhile

Reputation: 18202

Find the level of Deepest child Treenode

I have treenode & i would like to find the deepest child in the treenode. if there are 2 child nodes with level 11 & level 13 respectively then i need unction to return me the value 13.

How can i do that ?

public int FindLevel(TreeNode oParentNode)
{
   counter++;
  forech(TreeNode oSubNode in oParentNode.Nodes)
  {
    FindLevel(oParentNode);
  }

 return Counter;
}

Upvotes: 5

Views: 8276

Answers (3)

Victor.Miranda
Victor.Miranda

Reputation: 11

This is the fast way to get level´s deep of selected node.

 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {
        TreeNode node = treeView1.SelectedNode;
        MessageBox.Show(string.Format("You selected: {0}{1}", node.Text,e.Node.Level));

    }

Upvotes: -2

Szybki
Szybki

Reputation: 1111

Here's the extension method for TreeView that returns Level of the deepest node in that TreeView.

public int GetDeepestNodeLevel(this System.Windows.Forms.TreeView treeView)
{
    int level = -1;
    foreach (System.Windows.Forms.TreeNode node in treeView.Nodes) {
        int deep = DigInNodes(node);
        if (deep > level)
            level = deep;
    }
    return level;
}
private int DigInNodes(System.Windows.Forms.TreeNode node)
{
    int level = node.Level;
    foreach (System.Windows.Forms.TreeNode subnode in node.Nodes) {
        int deep = DigInNodes(subnode);
        if (deep > level)
            level = deep;
    }
    return level;
}

Code is tested and works for me.

Upvotes: 1

Fischermaen
Fischermaen

Reputation: 12468

Here is my suggestion for you:

private int GetDeepestChildNodeLevel(TreeNode node)
{
    var subLevel = node.Nodes.Cast<TreeNode>().Select(GetDeepestChildNodeLevel);
    return subLevel.Count() == 0 ? 1 : subLevel.Max() + 1;
}

here with explicit types:

private int GetDeepestChildNodeLevel(TreeNode node)
{
    var subLevel = node.Nodes.Cast<TreeNode>().Select<TreeNode, int>(subNode => GetDeepestChildNodeLevel(subNode));
    return subLevel.Count<int>() == 0 ? 1 : subLevel.Max() + 1;
}

Upvotes: 10

Related Questions