Click here to Skip to main content
16,020,568 members
Articles / Web Development / ASP.NET

ASP.NET Tree View - with customized tree nodes

Rate me:
Please Sign up or sign in to vote.
3.38/5 (9 votes)
12 May 2006CPOL3 min read 195.8K   4.4K   43   12
This article details how to setup the IE Web Control's TreeView programmatically with customized tree nodes.

Sample screenshot

Introduction

TreeView control is one of the most useful controls comes with the Microsoft IE WebControls.

I have used Microsoft IE web control (free download) for this sample application.

You may download the Microsoft IE web control from the following link.

http://asp.net/IEWebControls/Download.aspx?tabindex=0&tabid=1.

I have attached the soucecode in the following files TreeViewSample.aspx file and TreeViewSample.aspx.cs files. Please go through the attached files.

  1. You may refer the above URL to understand how to set the reference and add the IE webControl into your web project. Due to time limitation I may not able to give step by step instructions to create the Treeview control in  your web page. Please excuse me!!

I have created this control as part of my current project when I failed to find a customized Tree control which satisfy my requirements in the net ;-) .

However I have referred Mr. Steve Sharrok's article about TreeView Control  (You can view his article from the folowing link http://aspalliance.com/articleViewer.aspx?aId=125&pId=).

In the given example I tried to populate the TreeView control with the folders and files as Steve did.

But there are some differences in this TreeView control. Here each of the node contains a hyperlink (which actually points to http://www.google.com/ -  You can make it point to any web page as per your wish) and a HTML input button.

This is just a demonstartion of how can we achieve the treenodes with other user controls.

Please follow the given steps to create a Treeview Control in your ASP.NET application.

  1. Make sure that you have installed Microsoft IE web controls in your system.
  2. Add the Microsoft IE web controls reference to the newly created project.
  3. Reference
  4. Create a blank ASP.NET project
  5. Add a webform named Sample.aspx and delete the content of Sample.aspx file except the first line from the HTML view.
  6. Paste the follwoing code from the SampleTreeview.aspx attached with this article into sample.aspx file after the existing first line.       
  7. <%@ Register TagPrefix="iewc" Namespace="Microsoft.Web.UI.WebControls" Assembly="Microsoft.Web.UI.WebControls" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
     <body MS_POSITIONING="GridLayout">
     <script language="javascript">
     function clickedMe()
     {
      alert('hey, why did you click me ???');
     }
      </script>
      <form id="TreeViewSample" method="post" runat="server">
       <table id="Table1" height="100%" cellSpacing="0" cellPadding="8" border="0">
        <tr height="100%">
         <td vAlign="top"><iewc:treeview id="TreeCtrl" runat="server" SelectedStyle="background:white;color:black;font-size=16;font-weight:bold"
           HoverStyle="border=solid 1px;color=black;background:white;font-size=16;font-weight:bold" SystemImagesPath="/PopupWindow-POC/images/treeimages/"
           DefaultStyle="background:white;color:black;font-size:16;font-weight:bold" ShowLines="False" ShowToolTip="False"
           Width="600"></iewc:treeview></td>
        </tr>
       </table>
      </form>
     </body>
    
  8. Make sure that your SystemImagesPath pointing to a valid path. If you have installed Microsoft IE webcontrols and followed the steps required for the installtion you will have all the tree images under the folder webctrl_client\1_0 folder in your default website. For avoiding confusion I have copied the image folder into my application folder. (/PopupWindow-POC/images).
  9. Now go to the Sample.aspx.cs file and replace the page_load function with the following code.Please note that the root folder for the tree is pointing to TestData folder. So please download TestData folder from the attached zip file and keep it in your application folder since I'm using the mappath to retreive the TestData folder.
  10. private void Page_Load(object sender, System.EventArgs e)
      {
       if ( !this.IsPostBack)
       {
        TreeNodeType type;
    
        type = new TreeNodeType();
        type.Type = "folder";
        TreeCtrl.TreeNodeTypes.Add( type );
    
        type = new TreeNodeType();
        type.Type = "file";
        TreeCtrl.TreeNodeTypes.Add( type );
    
        // start the recursively load from our application root path
        //  (we add the trailing "/" for a little substring trimming below)
        GetFolders( MapPath( "~/TestData" ), TreeCtrl.Nodes );
    
        // expand 3 levels of the tree
        TreeCtrl.ExpandLevel = 3;
       }
      }
    
  11. Now add the follwoing 2 functions from SampleTreeView.aspx.cs file from the attached zip file inot the Sample.aspx.cs file.
  12. C#
    // recursive method to load all folders and files into tree
      private void GetFolders(  string path, TreeNodeCollection nodes )
      {
       // add nodes for all directories (folders)
       string[] dirs = Directory.GetDirectories( path );
       foreach( string p in dirs )
       {
        string dp = p.Substring( path.Length );
        nodes.Add( Node( "", p.Substring( path.Length + 1), "folder" ) );
       }   
    
       // add nodes for all files in this directory (folder)
       string[] files = Directory.GetFiles( path, "*.*" );
       foreach( string p in files )
       {
        nodes.Add( Node( p, p.Substring( path.Length ), "file" ) );
       }   
    
       // add all subdirectories for each directory (recursive)
       for( int i = 0; i < nodes.Count; i++ )
       {
        if ( nodes[ i ].Type == "folder" )
        {
         GetFolders( dirs[ i ] + "\\", nodes[i ].Nodes );
        }
       }    
      }
  13. C#
    // create a TreeNode from the specified path, text and type
      private TreeViewSample Node( string path, string text, string type )
      {
       TreeNode n = new TreeNode();   
       n.Type = type;   
       StringBuilder nodeText =  new StringBuilder();
       if ( type == "file" )
       {
        _idNumber++;
        nodeText.Append(@"<table border=""0"" cellpadding=""0"" cellspacing=""0""><tr><td width=""100px"">") ; 
        nodeText.Append(@"<b><a style=""text-decoration:none;cursor:default;background:white;color:black;font-size:16;font-weight:bold"" href=""javascript:void(0)""");
        nodeText.Append(@"> ").Append(text.Trim()).Append("</a></b>");
        nodeText.Append(@"</td><td width=""150px"">");  
        nodeText.Append(@"<b><a style=""background:white;color:red;font-size:16;font-weight:bold"" href=""<a href="%22http://www.google.com/%22">http://www.google.com/</a>""");
        nodeText.Append(@">www.google.com </a></b>");
        nodeText.Append(@"</td><td width=""100px"">");
        nodeText.Append(@"<INPUT id=""").Append(_idNumber.ToString()).Append(@""" type=""button"" onclick=""javascript:clickedMe()"" value=""Click Me!"">");
        nodeText.Append(@"</td></tr></table>");  
       }
       else if ( type == "folder" )
       {
        nodeText.Append(@"<table border=""0"" cellpadding=""0"" cellspacing=""0""><tr><td width=""100px"">") ; 
        nodeText.Append(@"<b><a style=""text-decoration:none;cursor:default;background:white;color:black;font-size:16;font-weight:bold"" href=""javascript:void(0)""");
        nodeText.Append(@"> ").Append(text.Trim()).Append("</a></b>");
        nodeText.Append(@"</td></tr></table>");
       }
       n.Text = nodeText.ToString();
     
       return n;
      }
  14.   Please add all the namespaces required for successful compilation. You may use the TreeviewSample.aspx.cs file for your reference.
  15. using System;
    using System.IO;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text; 
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using Microsoft.Web.UI.WebControls;
    C#
    Build your project and execute.

I know this article is not complete to its extend. Since currently I'm working in a tight scheduled project I couldnt update the article with more details. 

 

 

 

 

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Rohith Gopi11-Oct-12 0:02
Rohith Gopi11-Oct-12 0:02 
Generalgeneral Pin
punitha subramanian1-Sep-12 3:59
punitha subramanian1-Sep-12 3:59 
QuestionQuestion about tooltip Pin
HankAnzis21-Oct-08 8:39
HankAnzis21-Oct-08 8:39 
QuestionSelectedNodeChanged doens not work? Pin
wangs13-Jan-08 5:52
wangs13-Jan-08 5:52 
GeneralthnX Pin
Talha Aziz4-Jul-07 22:53
Talha Aziz4-Jul-07 22:53 
Question.NET 2005 Pin
LeleHalfon7-Mar-07 12:30
LeleHalfon7-Mar-07 12:30 
Generalerror when install Pin
sasire1828-Mar-06 0:30
sasire1828-Mar-06 0:30 
GeneralRe: error when install Pin
Ishanth12-May-06 16:06
Ishanth12-May-06 16:06 
GeneralVery good Control Pin
huili_slsl12-Nov-05 22:08
huili_slsl12-Nov-05 22:08 
GeneralWrong URL Pin
Prasad Khandekar19-Sep-05 20:52
professionalPrasad Khandekar19-Sep-05 20:52 
GeneralRe: Wrong URL Pin
Ishanth20-Sep-05 3:10
Ishanth20-Sep-05 3:10 
GeneralRe: Wrong URL Pin
subri724-Mar-09 20:19
subri724-Mar-09 20:19 

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.