Loop through the tree

2 posts, 0 answers
  1. Julia Shah
    Julia Shah avatar
    47 posts
    Member since:
    Sep 2012

    Posted 20 Mar 2009 Link to this post

    Hi,

    I have a treeview that shows folders and documents. For each folder I have the number of child folders and child documents (one level down). How can I loop through the tree and calculate the total number of sub-folders and documents for each node?

    For example, this is what I have:

    Root (folders: 2, docs: 0)
            Folder 1 (folders: 2, docs: 1)
                    Folder 2 (folders: 0, docs: 0)
                    Folder 3 (folders: 0, docs: 1)
                            Document1.txt
                    Document2.txt
            Folder 4 (folders: 0, docs: 2)
                    Document2.txt
                    Document3.txt

    And this is what I need:

    Root (folders: 4, docs: 4)
            Folder 1 (folders: 2, docs: 2)
                    Folder 2 (folders: 0, docs: 0)
                    Folder 3 (folders: 0, docs: 1)
            Folder 4 (folders: 0, docs: 2)

    Thank you,
    Julia
  2. Atanas Korchev
    Admin
    Atanas Korchev avatar
    8462 posts

    Posted 23 Mar 2009 Link to this post

    Hi Julia Shah,

    You can use the Nodes property to obtain the immediate child nodes of a particular node. You could use it to traverse a particular node and calculate the total number of folders. You also need to use recursion in order to go deeper than the immediate child nodes. Here is a quick code snippet

    public int CalculateSubFolders(RadTreeNode parent)
    {
           int result = 0;

           foreach (RadTreeNode child in parent.Nodes)
          {
                  if (IsFolder(child)) // This method determines if a node is a folder
                 {
                       result ++; // increment for the "child" node
                       result += CalculateSubFolders(child); //add the number of folders in the child node.
                 }
          }
           return result;
    }

    Regards,
    Albert
    the Telerik team

    Check out Telerik Trainer , the state of the art learning tool for Telerik products.
Back to Top