Click here to Skip to main content
15,885,537 members
Articles / Programming Languages / Visual Basic

Fill a Tree

Rate me:
Please Sign up or sign in to vote.
1.62/5 (11 votes)
2 Sep 2004CPOL1 min read 40.4K   1.1K   12   2
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)


Written By
Web Developer
Croatia Croatia
VB programmer with MCSD status. Loves chevapi...

Medo's Home Page

Comments and Discussions

 
GeneralGreat Program Pin
aaroncampf1-Jan-11 9:37
aaroncampf1-Jan-11 9:37 
GeneralArticle Pin
Paul Watson4-Sep-04 13:34
sitebuilderPaul Watson4-Sep-04 13: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.