Click here to Skip to main content
Click here to Skip to main content

Tree Chart Generator

, 18 Nov 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on the development of a Tree Chart Generator


There is, in organizations, a constant need to display tree structures. This can be done for file systems, Organization charts, Bill of Material, etc. This article discusses a component which can generate an image of the required tree, based on the data in a DataTable. The DLL can be called from Windows Forms or ASP.NET. Most of the parameters (sizes, colors) can be controlled by the developer using the DLL; they are exposed as properties.

This first version of this DLL was called OrgChart Generator and was published here. During development of a BOM display application, it became obvious that the Org chart Generator lacks a few very important issues:

  1. It was too specific: the DLL is a Tree generator and should be named as such.
  2. A node in the Tree could not appear twice. An Employee may work for more than one department.
  3. The data structure used (both an XmlDocument and a SortedDictionary) was not good enough.

So, it became necessary to rewrite the whole application and give it a new name. Hence, this article.

Using the Code

The download ZIP file contains the C# solution, which has two projects:

  1. TreeGenerator, which contains the code for the DLL that generates the Tree image
  2. TestTreeGenerator, which contains a Windows Forms application that demonstrates the abilities of TreeGenerator and its usage.


The TreeGenerator accepts a Typed DataTable in the constructor, with the node list, in order to generate the tree. The TreeData.TreeDataTableDataTable is the DataTable that the class will accept in the constructor. It can contain the whole tree structure or just parts of it. If it contains the whole tree, multiple miniTrees can be created from the same instance of the object. The structure of the DataTable is as follows:

  • string nodeID - Primary Key - the ID of the node - employee number, item code or anything else that uniquely identifies the node
  • string parentNodeID - Primary Key - The ID of the node parent. This defines the tree structure. It may be String.Empty
  • string nodeDescription - A short description for the node
  • string nodeNote - A note for the node


There is just one main method, GenerateTree, which is overloaded. The difference between the overloads is that one method accepts as parameters the required size of the resulting image and resizes it before returning it. The other returns it in the size as determined by calculation - the number of boxes (both x & y) times the number of nodes.
This method returns a System.IO.Stream , which can be used to display an image, save to file, or any other activity. Another important parameter for this method is the StartFromNodeID. This parameter determines which node will be at the top of the tree.

Another method exists mainly as a helper method. getRectangleFromNode is used internally, but can also be used externally to return the Rectangle of the node coordinates, based on the XmlNode. This class/DLL can be used from a Windows Forms application in the following way:

//First - create the DataTable. In real life it would be extracted from a DB
//or created some other way. 
private void Form1_Load(object sender, EventArgs e) {
            TreeGenerator.TreeData.TreeDataTableDataTable dtTree = 
			new TreeData.TreeDataTableDataTable(); 
            dtTree.AddTreeDataTableRow("1000", "","1000",""); 
            dtTree.AddTreeDataTableRow("2000", "1000","2000",""); 
            dtTree.AddTreeDataTableRow("2001", "1000","2001",""); 
            dtTree.AddTreeDataTableRow("3000","2000", "3000",""); 
            dtTree.AddTreeDataTableRow("3001", "2000", "3001",""); 
            dtTree.AddTreeDataTableRow("3000", "2001", "3000",""); 
            dtTree.AddTreeDataTableRow("4000", "3000", "4000",""); 
            dtTree.AddTreeDataTableRow("4001", "3000", "4001", ""); 
          //instantiate the object 
          myTree = new TreeBuilder(dtTree);    
        //Now - Generate the tree itself
        picTree.Image = Image.FromStream(


The image that is returned has default properties. In order to control the sizes and colors of the Tree, these properties can be changed (all sizes are in pixels):

  • BoxFillColor - Which color will fill the boxes
  • BoxWidth - The width of each box
  • BoxHeight - The height of each box
  • Margin - The margin from the edges of the image to the boxes
  • HorizontalSpace - The space between the 2 employee boxes on the same level
  • VerticalSpace - The space between 2 levels of employees
  • FontSize - The font size for the node details
  • LineColor - The color of both the box line and the connecting line
  • LineWidth - The width of both the box line and the connecting line
  • BGColor - The color in the Background of the image
  • FontColor - The font color
  • xmlTree - An XmlDocument containing all the tree data, including the position of each node on the chart. This can be used for checking if a specific node was clicked.

Changing these properties could generate weird results, so care should be taken by the user. For example, it would not look good if both the BoxFillColor and the FontColor were the same.

Trapping MouseClick Events

Using the xmlTree property, it can be determined where the user clicked. Below is an example for a Windows Forms application. This will not work for ASP.NET.

private void picOrgChart_MouseClick(object sender, MouseEventArgs e)
            Rectangle currentRect;
            //determine if the mouse clicked on a box, 
            //if so, show the node description.
            string SelectedNode = "No Node";
            //find the node
            foreach (XmlNode oNode in myTree.xmlTree.SelectNodes("//Node"))
                //iterate through all employees until found.
                currentRect = myTree.getRectangleFromNode(oNode);
                if (e.X >= currentRect.Left &&
                    e.X <= currentRect.Right &&
                    e.Y >= currentRect.Top &&
                    e.Y <= currentRect.Bottom)
                    SelectedNode = 


Using this code in ASP.NET requires two pages (see attached ZIP file):

  1. ShowTree.aspx - Accepts the user input and shows the image
  2. OrgChartImage.aspx - Generates the image and returns it to the calling page.


The page contains a textbox that accepts any input. Whatever the user typed will become the top node of the tree. In real life, the textbox (or DDL, or any other control) will accept only employee ID, Item Code, etc. Clicking on the "Show Tree" button will show the tree for the typed in name. In this case, it will be a randomly generated tree. In real life, the tree data should be selected from a database.

Clicking on any of the tree nodes will show the child nodes of that node, in a new tree. It is possible, instead of showing a new tree each time, to enlarge the tree all the time, by keeping the tree dataTable as a static object.

The main function in this page is the one that generates the image. The image can be shown as an imageMap, or any other image tag. In this case, the imageMap.ImageUrl is linked to the page which reads the image from the cache and returns it as a stream.
This function also gets the XmlDocument from the TreeGenerator object and defines the hotspots for the imageMap.

private void GenerateChart(string mItem) 
        //create the chart object 
        TreeGenerator.TreeBuilder currentBOM       
            = new TreeGenerator.TreeBuilder(GetDT(mItem));
        //specify visual properties
        currentBOM.HorizontalSpace = 15;
        currentBOM.VerticalSpace = 15;
        currentBOM.FontSize = 7;
        currentBOM.BoxHeight = 80;
        currentBOM.BoxWidth = 80;
        currentBOM.LineColor = 
        currentBOM.FontColor = 
           System.Drawing.Image OC = 
              mItem, System.Drawing.Imaging.ImageFormat.Bmp)); 
           string nameOfImage =
        Session.SessionID + "CurrentImage"; 
        //save in the cache, to be used by the page creating the image 
        Cache.Insert(nameOfImage, OC, null, 
           CacheItemPriority.NotRemovable, null); 
        //update the item image map 
        //supply the image name by querystring 
        impBOM.ImageUrl = "~/OrgChartImage.aspx?ID=" + nameOfImage;
        //remove all hotspots 
        //regenerate the hotspots. 
        foreach (XmlNode oNode in currentBOM.xmlTree.SelectNodes("//Node")) 
        RectangleHotSpot RectHS
            = new RectangleHotSpot();
            RectHS.HotSpotMode = HotSpotMode.PostBack; Rectangle
            currentRect = currentBOM.getRectangleFromNode(oNode);
            RectHS.Top = currentRect.Top;
            RectHS.Bottom = currentRect.Bottom;
            RectHS.Left = currentRect.Left;
            RectHS.Right = currentRect.Right;
            RectHS.PostBackValue = oNode.Attributes["nodeID"].InnerText;
              = oNode.Attributes["nodeDescription"].InnerText; 


This page loads the cache item based on the passed parameter, converts it into an image and writes it into the output stream. There is only one function here:

protected void Page_Load(object sender, EventArgs e)
        // Change the response headers to output a JPEG image.
        this.Response.ContentType = "image/jpeg";
        System.Drawing.Image OC = null;
        //Build the image 
        string imageName = Request.QueryString["ID"];
        if (Cache[imageName] != null)
            OC = (System.Drawing.Image)Cache[imageName];
            // Write the image to the response stream in JPEG format.
            OC.Save(this.Response.OutputStream, ImageFormat.Jpeg);


  • 16th September, 2007 - Initial release
  • 23rd September, 2007 - Added ASP.NET usage sample


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


About the Author

Rotem Sapir
Web Developer
Israel Israel
No Biography provided

Comments and Discussions

QuestionHow to view the whole tree(i tried making the TreeGenerator.TreeData.TreeDataTableDataTable Result as static, still it shows the new tree every time i click on a node)? PinmemberMember 947014824-Aug-14 3:23 
QuestionThe code is not compatible with VB.Net PinmemberAhmad Al-Mutawa15-May-14 3:26 
QuestionIs there an option to build the chart vertically? Pinmembersiddb7519-Nov-13 8:31 
QuestionHow to add an image to the hierachy PinmemberJazzyJay6-Jun-13 17:12 
QuestionExcellent work PinmemberJazzyJay5-Jun-13 16:54 
GeneralThanks Pinmembersaerluvla Arul20-Dec-12 23:26 
QuestionError whe trying to launch the Test Chart Generator PinmemberMember 934142931-Aug-12 6:25 
GeneralNice Article .But How can i Bind it to a Database [modified] PinmemberKishoreSrinu27-Jul-12 3:16 
GeneralMy vote of 5 Pinmembervatzsri15-Mar-12 5:17 
Questionwill u plz tell me how we can generate binary tree with increament numbers(not random numbers) ? Pinmemberanurag917920-Feb-12 21:17 
QuestionIssue in the postbackvalue of imagemap click event Pinmemberpriyankags12-Jan-12 21:24 
Questionhi... nice project PinmembershipMe7-Dec-11 17:13 
QuestionImage Quality Pinmemberstani050217-Oct-11 0:59 
Questionchange node color PinmemberLipKee4-Jul-11 0:53 
Generalgreat Pinmemberameytov10-Jun-11 13:59 
Generalnot able to use it in web application [modified] Pinmembersvknair3-May-11 0:59 
Generalneed help to use it from database [modified] Pinmembersvknair2-May-11 22:07 
GeneralRe: need help to use it from database [modified] PinmemberJazzyJay6-Jun-13 17:25 
GeneralImage not working on server Pinmemberavinash s27-Apr-11 2:25 
GeneralRe: Image not working on server Pinmemberkshitij_mehta10-Aug-11 18:01 
GeneralContact for more developement PinmemberGal9921-Apr-11 3:09 
GeneralNeed help When child node is in same line of Parent PinmemberMember 294169218-Jan-11 9:03 
Hi Rotem,
Thank you for your wonderful code. However I have one small request.In my application I would like to show one of the child node in the same line of parent node.
I tried to make changes in Build Tree and DrawChart but thing is I cannot draw Secretary node(X, Y points) before the parent node..
I will really appreciate your help.
For eg :
Secretary node on the left side of Parent(Director) ideally chart will look like this..
Director ------ Secretary
Deputy Director ----- Secretary
Child Node 1 Child node 2 Child node 3 and so on....
Thank you
Meenal Gore
GeneralRe: Need help When child node is in same line of Parent PinmemberRotem Sapir23-Jan-11 21:52 
GeneralError: Column 'nodeID, parentNodeID' is constrained to be unique. PinmemberMurthy Pothukuchi18-Jan-11 3:18 
GeneralRe: Error: Column 'nodeID, parentNodeID' is constrained to be unique. PinmemberRotem Sapir23-Jan-11 21:55 
GeneralRe: Organization Chart Control for Winforms and ASP.NET Webforms - Free PinmemberRotem Sapir5-Dec-10 11:13 
GeneralOut of Memory Error - Exception Pinmemberketan5411-Dec-10 17:47 
GeneralRe: Out of Memory Error - Exception PinmemberRotem Sapir5-Dec-10 11:06 
GeneralSystem.OutOfMemoryException Pinmemberketan54129-Nov-10 21:59 
GeneralI'm getting a red "X" only Pinmemberdigidigi3323-Dec-09 7:38 
GeneralRe: I'm getting a red "X" only PinmemberRotem Sapir24-Dec-09 10:29 
GeneralGreat Job Pinmemberwww042815-Oct-09 3:32 
GeneralRe: Great Job PinmemberRotem Sapir23-Oct-09 0:01 
GeneralRe: Great Job [modified] Pinmembercris033412-Nov-09 8:33 
GeneralRe: Great Job PinmemberRotem Sapir14-Nov-09 23:28 
Generalset image width and height Pinmemberkieran540515-Jul-09 4:51 
GeneralRe: set image width and height PinmemberRotem Sapir23-Oct-09 0:00 
GeneralThanx Pinmemberusmanmughal14-Jul-09 22:12 
GeneralRe: Thanx PinmemberRotem Sapir15-Jul-09 2:38 
GeneralPlz help me Pinmemberusmanmughal11-Jul-09 0:50 
AnswerRe: Plz help me PinmemberRotem Sapir13-Jul-09 2:11 
GeneralRe: error "Parameter is not valid" Pinmembersfghk9-Mar-09 2:34 
GeneralRe: error "Parameter is not valid" PinmemberRotem Sapir10-Mar-09 21:03 
GeneralAdded Images url to the dataset to draw person's image in the tree PinmemberSheikh Nabeel Moeen26-Feb-09 19:47 
GeneralRe: Added Images url to the dataset to draw person's image in the tree Pinmembergabo15-Apr-09 12:09 
GeneralRe: Added Images url to the dataset to draw person's image in the tree PinmemberRotem Sapir15-Apr-09 22:35 
QuestionCreating Image with N-Level of tree and huge data crashes the application [modified] PinmemberSameer Kulkarni26-Feb-09 0:54 
AnswerRe: Creating Image with N-Level of tree and huge data crashes the application PinmemberRotem Sapir26-Feb-09 2:00 
GeneralRe: Creating Image with N-Level of tree and huge data crashes the application PinmemberSameer Kulkarni26-Feb-09 23:47 
GeneralRe: Creating Image with N-Level of tree and huge data crashes the application PinmemberRotem Sapir3-Mar-09 2:15 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 18 Nov 2007
Article Copyright 2007 by Rotem Sapir
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid