Click here to Skip to main content
13,589,109 members
Click here to Skip to main content
Add your own
alternative version


86 bookmarked
Posted 10 Dec 2008
Licenced CPOL

Hierarchical Tree Represented by Modified Preorder Tree Traversal Technique using C# 3.0 and SQL 2005.

, 10 Dec 2008
Rate this:
Please Sign up or sign in to vote.
Gathering of various algorithms into one library to transform Hierarchical trees between various formats, and allows them to be represented into SQL2005, the formats supported are TreeView, Textual, Tabular, Modified Preorder Tree Traversal and Graphical.


During my work in a (CMS) Content Management System, and in the module of Content-mapping (which is a .NET desktop application) I needed to classify my contents into a chain of categories like hierarchical tree, but I also needed to represent that tree into more than a format, such as Textual, Tabular, Nodes and Database.

I searched the web about which .NET library is going to represent my tree into the SQL2005 database. I couldn't found that library, but I found an article (Gijs Van Tulder) is titled Storing Hierarchical Data in a Database that explains the concept of the MPTT (Modified Preorder Tree Traversal). Unfortunately, it was written for PHP developers, so, I translated the concept into C# and SQL2005 code. Moreover, I wrote some algorithms to represent trees into textual, tabular, tree view nodes and graphical format. I also used provider model techniques as a step to support various databases such as SQLite.

Finally, I gathered all these staff into one project, but, the entire classes could be easily reused and separated into class libraries, even the innovative algorithms (that I wrote) could be reused individually like the one that is written to render the graphical representation of the tree.

Now I think that I have an efficient way to add, insert, delete and retrieve tree-elements using many ways including a way for SQL2005 database with a very effective schema, which is MPTT that minimizes the number of database queries by having just one query for each activity.

What is Hierarchical Tree?

Simply, it is a structure of data that looks like a real tree, even though the hierarchical-tree is generally shown upside down compared with a real tree; that is to say with the root at the top and the leaves at the bottom, elements of that structure are related with each other by a parent-child relationship, those relationships are represented by a connecting-lines between elements and they are called "Branches", moreover, elements that have no superior are called "ROOTs" and elements that have no children are called "Leaves".

The following example demonstrates a textual representation for the Animal-kingdom tree:

Animal Kingdom
#No Backbones
##Jointed Legs
Figure 1: Hierarchical tree, textual representation.

So we have 1 root (Animal Kingdom) and 12 leaves (Mammal, Lungs, Reptile, Bird, Fish, Amphibian, Starfish, Snail, Clam, Insect, Spider, Crustacean), we have 18 lines where each line contains one tree element/node, the count of (#)s in front of the node-title represents the depth level of the element in the tree, and elements that have the same level and have the same parent are called "SIBLINGs".

A graphical representation of such trees exist in Figure 2, where a rectangle is a symbolic representation of a node, and also a tabular representation for such trees exist in Figure 3.


Figure 2: Hierarchical tree graphical representation.
IDParent IDTitleLeftRight
10Animal Kingdom136
101No Backbones1835
1510Jointed Legs2734
Figure 3: Hierarchical tree tabular representation.

Using the Demo Project

Back to the previous section, copy the text of Figure 1, and paste it into the TextBox of the right hand side on the interface of demo project, then, press the button that is titled "<<" to convert the text into the traditional tree representation in the TreeView control in the left hand side.

Show a tabular representation of the tree by clicking the radio button that is called "Tabular," and toggle between textual and tabular using the the other radio button that is called "Textual".

To save the tree you just converted into SQL2005 database you should first select an existing database, but you don't have to create any tables, just construct a working connection-string by clicking the button that is called "Connection String," after composing the connection string, simply click the button that is called "Save" to save the tree into a table called "tblTree," the table will be created automatically if it does not exist or is truncated if it is existing.

Of course, you could load this tree any time again from the same connection-string if you provided it correctly, just compose the connection string and click the "Load" button. However, you don't have to enter the connection string each time you open the demo project, it saves the connection string into a file named constring.txt automatically.

Now you can enjoy showing the graphical representation of the tree by clicking the "Draw" button.

Using the Code

You simply have to create an object from the MpttCoreEngine class and call any method from its interface.

MpttCoreEngine engine = new MpttCoreEngine();

This class contains all the algorithms that were written to represent hierarchical trees in various formats, the following list contains the most important methods in this class.

SetConnectionStringUse this function to provide a connection string to the engine
ConvertMpttIntoTreeUse this function to load tree nodes from the database
ConvertTreeIntoMpttUse this function to save tree nodes to database
ConvertTextIntoTreeConverts textual tree into TreeNode suitable to TreeView
ConvertTextTableIntoTreeConverts tabular tree into TreeNode suitable for TreeView
ConvertTreeIntoTextConverts TreeNode back to textual representation
ConvertTreeIntoTableConverts TreeNode back to tabular representation
DrawTreeDraws TreeNode on an Image and returns the Image for later use

The following code is a snapshot from the demo project which demonstrates how to use those methods.

private void LoadDb()
        TreeNode node = null;
        node = engine.ConvertMpttIntoTree();
        if (node != null)
    catch (Exception e)
        MessageBox.Show(e.Message +
                 "\r\nThe Connection string may not be correct");

private void SaveDb()
    if (treeView.Nodes.Count <= 0)
    catch (Exception e)
        MessageBox.Show(e.Message +
                 "\r\nThe Connection string may not be correct");

private void TreeReflection()
    char t = (delimiter.Text.Length > 0 ? delimiter.Text[0] : '#');
    engine.LevelDelimiter = t;
    TreeNode node = null;
    if (textual.Checked)
        node = engine.ConvertTextIntoTree(textView.Text, _delimiter, '*');
        node = engine.ConvertTextTableIntoTree(textView.Text, true);
    if (node != null)

private void TextReflection()
    if (treeView.Nodes.Count <= 0)
    char t = (delimiter.Text.Length > 0 ? delimiter.Text[0] : '#');
    engine.LevelDelimiter = t;
    if (textual.Checked)
        textView.Text = engine.ConvertTreeIntoText(treeView.Nodes[0], false);
        textView.Text = engine.ConvertTreeIntoTable(treeView.Nodes[0], false);

private void btnDraw_Click(object sender, EventArgs e)
    if (treeView.Nodes.Count <= 0)
    Bitmap bmp = engine.DrawTree(treeView.Nodes[0]);
    TreePreview preview = new TreePreview(bmp);

Points of Interest

The code is full of interest points, where most of them may need individual articles to explain. Here are the most important:

  1. 1- The algorithm of drawing the tree nodes is so complex, I used anonymous functions, recursion and callbacks to calculate accurate locations for the nodes. You can find that algorithm on the function DrawTree.
  2. The MPTT concept is explained in several places on the web, though, I composed that concept with a design pattern known by "provider model", where, an abstract class called TreeProvider is created to be implemented and supports any database type like SQL2005, MySQL or SQLite.
  3. You could simply separate the core of the demo projects into a class library by copying only the folder named Core to any project you want.


Version 1.0:

  1. TreeView representation
  2. Textual representation
  3. Tabular representation
  4. MPTT representation
  5. Graphical representation
  6. SQL2005 support


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


About the Author

Wael Alghool
Architect Government
Qatar Qatar
Programmer since 1990 with Pascal, VC++, C#, ASP.NET, jQuery, J2EE and Android.
PMP Certified since 2009.
PSP Certified since 2005.
Business & System analyst since 2004.
Led teams in between 8 to 30 members.
Worked for,,,,

You may also be interested in...

Comments and Discussions

GeneralMy vote of 2 Pin
raiserle4-Oct-16 2:43
memberraiserle4-Oct-16 2:43 
GeneralMy vote of 5 Pin
ashumeerut5-Aug-13 20:48
professionalashumeerut5-Aug-13 20:48 
QuestionHow to use it in website Pin
ashumeerut5-Aug-13 20:04
professionalashumeerut5-Aug-13 20:04 
GeneralGreat Code Pin
ashumeerut5-Aug-13 19:59
professionalashumeerut5-Aug-13 19:59 
Questionwill it work for sqlite? Pin
lovingwind24-May-12 1:44
memberlovingwind24-May-12 1:44 
GeneralMy vote of 5 Pin
wasiuddin13-Oct-11 8:07
memberwasiuddin13-Oct-11 8:07 
GeneralQuestions Pin
BBBrrriiiaaannn10-Oct-09 11:41
memberBBBrrriiiaaannn10-Oct-09 11:41 
Generaluse this code for Silverlight 3 TreeView via MVVM Pin
Greg Hazzard31-Jul-09 2:32
memberGreg Hazzard31-Jul-09 2:32 
GeneralIts a great technique, but... Pin
Adrian Schröder19-Jul-09 21:00
memberAdrian Schröder19-Jul-09 21:00 
QuestionPlease advise me... Pin
Devil_Ashutosh16-Jun-09 0:11
memberDevil_Ashutosh16-Jun-09 0:11 
AnswerRe: Please advise me... Pin
Wael Alghool19-Jun-09 9:05
memberWael Alghool19-Jun-09 9:05 
GeneralI could not find a solution file Pin
asanka_nilath30-Apr-09 3:08
memberasanka_nilath30-Apr-09 3:08 
GeneralRe: I could not find a solution file Pin
Wael Alghool30-Apr-09 6:39
memberWael Alghool30-Apr-09 6:39 
Generali'm searching for a solution with HierarchyID Pin
hapalu7-Apr-09 6:12
memberhapalu7-Apr-09 6:12 
GeneralRe: i'm searching for a solution with HierarchyID Pin
Wael Alghool10-Apr-09 4:58
memberWael Alghool10-Apr-09 4:58 
GeneralRe: i'm searching for a solution with HierarchyID Pin
hapalu15-Apr-09 22:06
memberhapalu15-Apr-09 22:06 
GeneralIts Great Sir. Pin
vicky95-Feb-09 20:42
membervicky95-Feb-09 20:42 
GeneralRe: Its Great Sir. Pin
Wael Alghool7-Feb-09 22:41
memberWael Alghool7-Feb-09 22:41 
Generalgood job Pin
Eka Abdurachman17-Jan-09 21:52
memberEka Abdurachman17-Jan-09 21:52 
GeneralExcellent Pin
Dr.Luiji11-Dec-08 11:46
memberDr.Luiji11-Dec-08 11:46 
GeneralRe: Excellent Pin
Wael Alghool11-Dec-08 22:43
memberWael Alghool11-Dec-08 22:43 
GeneralRe: Excellent Pin
Dr.Luiji12-Dec-08 1:19
memberDr.Luiji12-Dec-08 1:19 
GeneralRe: Excellent Pin
vicky95-Feb-09 20:40
membervicky95-Feb-09 20:40 

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 | Cookies | Terms of Use | Mobile
Web03-2016 | 2.8.180615.1 | Last Updated 10 Dec 2008
Article Copyright 2008 by Wael Alghool
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid