Click here to Skip to main content
Licence CPOL
First Posted 2 Sep 2004
Views 27,735
Downloads 798
Bookmarked 12 times

Fill a Tree

By | 2 Sep 2004 | Article
I sometime need to show things in tree manner. This is not big problem unless you try to fill it from database. Since in .NET there is no key and child adding like in VB6 things have to be done recursively.

Introduction

First we must discuss database format. Only requirement here is need for two fields - ID, ParentID and one Text field. All other fields are optional. For this occasion I have prepared small database with that structure.

Since there can not be more than one DataReader per Connection we can not use recursion right away. Instead, for step one, we will prepare buffer array to hold all required data. This will be few times faster than using one step recursion but it will consume memory like crazy. I think that this solution will do since trees are usually not very big. For this step we user "FillTree" method in DBTree class. This method takes tree object as only parameter and after filling buffer it goes to step two.

Step two is recursion itself. It is contained in "RecurTree" method and takes tree, parentNode and parentID as arguments. Since tree is same as in first step there is not much explanation here. parentNode argument is here for propagation of current node parent throughout recursion. In first step we send value Nothing instead since there is no parent there. If this is case new node will be added to tree itself. ParentID is essentially same thing but used for purpose of filtering out nodes that are irrelevant in current recursion pass. In first pass we send here 0 value since we consider items with parentID=0 to be roots.

And that's all. I think that all of this will be much clearer if you check source.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Josip Medved (unused)

Web Developer

Croatia Croatia

Member

VB programmer with MCSD status. Loves chevapi...

Medo's Home Page

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGreat Program Pinmemberaaroncampf9:37 1 Jan '11  
GeneralArticle PinsitebuilderPaul Watson13:34 4 Sep '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 3 Sep 2004
Article Copyright 2004 by Josip Medved (unused)
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid