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;
}
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With