How to get the depths of TreeNode in C# Code without Click event ?

what's the mean about title forexample.

sample code.

public int Depth(TreeNode node)

{

int _depth;

TreeNode tmpNode = node;

while(tmpNode.Parent != null)

{

//Error: could not convert Parent(is object) to TreeNode.

tmpNode = (TreeNode) tmpNode.Parent;

_depth ++;

}

return _depth;

}

running above code that fault and reason is : can't convert typeof parent from object to TreeNode.

but, how can i get depth of a TreeNode in my code with other method

please help me in hurry!

thanks.




Answer this question

How to get the depths of TreeNode in C# Code without Click event ?

  • Gunner54.

    Your cast is redunant, because the Parent property is allready of the TreeNode type.

    This code compiles with no problems:


    public int Depth(TreeNode node)
    {
    int depth = 0;
    TreeNode parent = node.Parent;

    while( parent != null )
    {
    parent = parent.Parent;
    depth++;
    }

    return depth;
    }




  • How to get the depths of TreeNode in C# Code without Click event ?