Click here to Skip to main content
13,289,626 members (60,044 online)
Click here to Skip to main content
Add your own
alternative version


12 bookmarked
Posted 2 Sep 2004

Fill a Tree

, 2 Sep 2004
Rate this:
Please Sign up or sign in to vote.
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.


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.


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
VB programmer with MCSD status. Loves chevapi...

Medo's Home Page

You may also be interested in...

Comments and Discussions

GeneralGreat Program Pin
aaroncampf1-Jan-11 10:37
memberaaroncampf1-Jan-11 10:37 
GeneralArticle Pin
Paul Watson4-Sep-04 14:34
sitebuilderPaul Watson4-Sep-04 14:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 3 Sep 2004
Article Copyright 2004 by Josip Medved (unused)
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid