Click here to Skip to main content
14,662,494 members
Articles » Web Development » ASP.NET Controls » General
Posted 14 Oct 2009


244 bookmarked

ASTreeView - Free ASP.NET TreeView Control

Rate this:
4.91 (119 votes)
Please Sign up or sign in to vote.
4.91 (119 votes)
19 Feb 2014CPOL
A full functional treeview control for ASP.NET, including drag and drop, Ajax loading, context menu, dropdown treeview.

Nuget Package 

ASTreeView is now on Please install using(for .Net Framework 4.0 and above): 

PM> Install-Package ASTreeView  

or if you target to .Net Framework 2.0/3.5, using: 

PM> Install-Package ASTreeView.Legacy  

Samples on Github 

The samples are now on github: 


ASTreeView is a full functional treeview control for ASP.NET with drag drop, Ajax loading, context menu, XML import/export, checkbox, selection, adding/editing/deleting nodes with Ajax.


ASTreeView is developed on .NET Framework 2.0. The demo project is a Visual Studio 2005 project. ASTreeView is compatible with ASP.NET 2.0 and above.

ASTreeView is FREE! That means you can use it anywhere!

I host the project on Google Code: please download the assembly and the demo, check out the demo, and use ASTreeView in your project!


I registered a domain name for astreeview:

Using the Code

Here are functionalities ASTreeView supports:

1. Drag & Drop

User can drag & drop nodes within the tree or even among trees!


See live demo:

<ct:ASTreeView ID="astvMyTree"
   EnableContextMenuAdd="false" />
In Code Behind
protected void btnToggleDragDrop_Click( object sender, EventArgs e )
	this.astvMyTree.EnableDragDrop = !this.astvMyTree.EnableDragDrop;
protected void btnToggleTreeLines_Click( object sender, EventArgs e )
	this.astvMyTree.EnableTreeLines = !this.astvMyTree.EnableTreeLines;
protected void btnToggleNodeIcon_Click( object sender, EventArgs e )
	this.astvMyTree.EnableNodeIcon = !this.astvMyTree.EnableNodeIcon;
protected void btnToggleCheckbox_Click( object sender, EventArgs e )
	this.astvMyTree.EnableCheckbox = !this.astvMyTree.EnableCheckbox;
protected void btnToggleDefaultNodeIcon_Click( object sender, EventArgs e )
	this.astvMyTree.EnableCustomizedNodeIcon = 
protected void btnToggleContextMenu_Click( object sender, EventArgs e )
	this.astvMyTree.EnableContextMenu = !this.astvMyTree.EnableContextMenu;

ASTreeView Demo

2. Tree Lines

Enable/Disable tree line is available.


See live demo:

3. Tree Node Icons

The developer can specify customized icon for each node, use default node icon, or, disable node icon.


See live demo:

4. Checkbox

Three-state (checked, unchecked, half-checked) checkbox is available.


See live demo:

5. Tree Node Context Menu

A user can use context menu to edit/delete node by right clicking the node. Ajax edit/delete is supported.


See live demo:

6. Multi-data Source Supported

A developer can bind different types of data source (currently astreeview supports datatable and XML datasource). Or developer can create ASTreeViewNode and append to the tree in the code.





See live demo:

7. Server-side Event Supported

OnSelectedNodeChanged and OnCheckedNodeChanged are available.

Image 8

See live demo:

<ct:ASTreeView ID="astvMyTree"
  OnOnSelectedNodeChanged="astvMyTree_OnSelectedNodeChanged" />
In Code Behind
protected void astvMyTree_OnCheckedNodeChanged
	( object src, ASTreeViewNodeCheckedEventArgs e )
	string toConsole = string.Format( ">>OnCheckedNodeChanged checked: 
		text:{0} value:{1} state:{2}", e.NodeText, e.NodeValue, 
		e.CheckedState.ToString() );
	this.divConsole.InnerHtml += ( toConsole + "<br />" );
protected void astvMyTree_OnSelectedNodeChanged( object src, 
				ASTreeViewNodeSelectedEventArgs e )
	string toConsole = string.Format( ">>OnSelectedNodeChanged selected: 
		text:{0} value:{1}", e.NodeText, e.NodeValue );
	this.divConsole.InnerHtml += ( toConsole + "<br />" );
protected void btnGetSelectedNode_Click( object sender, EventArgs e )
	string toConsole = string.Empty;
	ASTreeViewNode selectedNode = astvMyTree.GetSelectedNode();
	if( selectedNode == null )
		toConsole = ">>no node selected.";
		toConsole = string.Format( ">>node selected: text:{0} value:{1}", 
			selectedNode.NodeText, selectedNode.NodeValue );
	this.divConsole.InnerHtml += ( toConsole + "<br />" );
protected void btnGetCheckedNodes_Click( object sender, EventArgs e )
	List<ASTreeViewNode> checkedNodes = this.astvMyTree.GetCheckedNodes
			( cbIncludeHalfChecked.Checked );
	StringBuilder sb = new StringBuilder();
	foreach( ASTreeViewNode node in checkedNodes )
		sb.Append( string.Format( "[text:{0}, value:{1}]<br />", 
			node.NodeText, node.NodeValue ) );
	this.divConsole.InnerHtml += ( string.Format( ">>nodes checked: 
		<div style='padding-left:20px;'>{0}</div>", sb.ToString() ) );

8. Ajax Nodes Loading Supported

Having thousands of nodes? No problem, ASTreeView supports loading nodes using Ajax.


See live demo:

<ct:ASTreeView ID="astvMyTree" 



















In Code Behind
protected override void Render( HtmlTextWriter writer )
	if( Request.QueryString["t1"] == "ajaxLoad" )
		string virtualParentKey = Request.QueryString["virtualParentKey"];
		string para = string.Empty;// "= 1";
		if( virtualParentKey == null )
			para = " is NULL";
			para = "=" + virtualParentKey;
		string sql = @"SELECT p1.[ProductID] as 
		    ProductID, p1.[ProductName] as ProductName, 
		    p1.[ParentID] as ParentID, p3.childNodesCount as ChildNodesCount
FROM [Products] p1
	SELECT COUNT(*) AS childNodesCount , p2.[ParentID] AS pId 
	FROM [Products] p2
	GROUP BY p2.[ParentID]
) p3
ON p1.[ProductID] = p3.pId
WHERE p1.[ParentID] " + para;
DataTable dt = OleDbHelper.ExecuteDataset( base.NorthWindConnectionString, 
	CommandType.Text, sql ).Tables[0];
ASTreeViewNode root = new ASTreeViewNode( "root" );
foreach( DataRow dr in dt.Rows )
	string productName = dr["ProductName"].ToString();
	string productId = dr["ProductID"].ToString();
	string parentId = dr["ParentID"].ToString();
	int childNodesCount = 0;
	if( !string.IsNullOrEmpty( dr["ChildNodesCount"].ToString() ) )
		childNodesCount = int.Parse( dr["ChildNodesCount"].ToString() );
	ASTreeViewLinkNode node = new ASTreeViewLinkNode( productName, productId );
	node.VirtualNodesCount = childNodesCount;
	node.VirtualParentKey = productId;
	node.IsVirtualNode = childNodesCount > 0;
	node.NavigateUrl = "#";
	node.AddtionalAttributes.Add( new KeyValuePair<string, string>
			( "onclick", "return false;" ) );
	root.AppendChild( node );
HtmlGenericControl ulRoot = new HtmlGenericControl( "ul" );
astvMyTree.TreeViewHelper.ConvertTree( ulRoot, root, false );
foreach( Control c in ulRoot.Controls )
	c.RenderControl( writer );
else if( Request.QueryString["t2"] == "ajaxAdd" )
	string addNodeText = Request.QueryString["addNodeText"];
	int parentNodeValue = int.Parse( Request.QueryString["parentNodeValue"] );
	string maxSql = "select max( productId ) from products";
	int max = (int)OleDbHelper.ExecuteScalar
		( base.NorthWindConnectionString, CommandType.Text, maxSql );
	int newId = max + 1;
	string sql = string.Format( @"INSERT INTO products
	( productid, Discontinued, productname, parentid ) values( {0} ,0, '{1}', {2})"
	, max + 1, addNodeText.Replace( "'", "''" ), parentNodeValue );
	int i = OleDbHelper.ExecuteNonQuery
		( base.NorthWindConnectionString, CommandType.Text, sql );
	ASTreeViewNode root = new ASTreeViewNode( "root" );
	ASTreeViewLinkNode node = new ASTreeViewLinkNode
				( addNodeText, newId.ToString() );
	node.NavigateUrl = "#";
	node.AddtionalAttributes.Add( new KeyValuePair<string, 
			string>( "onclick", "return false;" ) );
	root.AppendChild( node );
	HtmlGenericControl ulRoot = new HtmlGenericControl( "ul" );
	astvMyTree.TreeViewHelper.ConvertTree( ulRoot, root, false );
	foreach( Control c in ulRoot.Controls )
		c.RenderControl( writer );
	base.Render( writer );			

9. Multi-type Tree Node

A tree node can be a hyper-link or LinkButton to perform postback.


See live demo

10. ASDropDownTree

ASDropDownTree inherits ASTreeView, looks like a DropDownList, multi-selection and single-selection are available by the control's configuration.


See live demo:

11. Drag & Drop Between (or Even Among) Trees

Nodes can be dragged and dropped across trees.


See live demo:

12. Extending ContextMenu

Now it is possible to add your customized ContextMenu Items to the menu. A screenshot:


To add your customized menu, it’s easy:

/// <summary>
/// initial controls, bind you events etc. here
/// </summary>
private void InitializeComponent()
    this.astvMyTree.ContextMenu.MenuItems.Add( new ASContextMenuItem( 
        "Custom Menu 1", "alert('current value:' + " 
        + this.astvMyTree.ContextMenuClientID
        + ".getSelectedItem().parentNode.getAttribute('treeNodeValue')" 
        + ");return false;", "otherevent" ) );
    this.astvMyTree.ContextMenu.MenuItems.Add( new ASContextMenuItem( 
        "Custom Menu 2", "alert('current text:' + " 
        + this.astvMyTree.ContextMenuClientID 
        + ".getSelectedItem().innerHTML" 
        + ");return false;", "otherevent" ) );

Online demo:

13. Extending ContextMenu

In version 1.3.0, the end user can open the folder by clicking on the node text. It is useful when only the leaf nodes are clickable, for example, bookmarks.


To enable this feature, just set the “EnableParentNodeExpand” property of ASTreeView.

14. Customize Node with HTML

NodeText can be HTML:

.AppendChild( new ASTreeViewLinkNode
	( "Accor <a href='' target='_blank'>see demo</a>"
, "Accor"
, "", "_self", "Goto Accor", "~/Images/demoIcons/accor.gif" )
	.AppendChild( new ASTreeViewLinkNode( "Accor Services", 
	"Accor Services",, 
	"_self", "Goto Accor Services", "~/Images/demoIcons/accorservices.gif" ) )
	.AppendChild( new ASTreeViewLinkNode( "Accor Hospitality", 
	"Accor Hospitality", "", "_self", 
	"Goto Accor Hospitality", "~/Images/demoIcons/accorhospitality.gif" ) )

15. Themes

ASTreeView now supports themes! A developer can easily create his own theme for the treeview. Check out the demo.



16. Right-To-Left Support

ASTreeView now supports RTL display, thank Mojtaba Vali for the suggestion! Also check out the demo.


17. HTML as TreeNodeText Supported

In the new version, you may use HTML as tree node text, not only plain text.


18. Multiline Edit Mode Supported

Set the EnableMultiLineEdit property to enable this feature, the default is false.


19. Drag and Drop Complete Event Now is Available.

I added a new client side event after drag and drop. to use:

<script type="text/javascript">
     //parameter must be "elem"
     function dndHandler( elem ){
         document.getElementById( "<%=divConsole.ClientID %>" ).innerHTML
                    += ( ">>node dragged:"
                         + elem.getAttribute("treeNodeValue")
                         + "<br />" );

and then set the OnNodeDragAndDropCompleteScript="dndHandler( elem )", visit demo.



20. New Property for ASTreeViewNode – EnableChildren

Set this property to false can disable dragging other nodes to the current node as child nodes. Please refer to sample 1 to see the effect.

21. Virtical Drag and Drop Nodes

If you use ASTreeView as a list, you can set EnableHorizontalLock to true, then the end user can only move the nodes up and down, not left nor right.



22. Fix Drag and Drop Depth

If you want the end user to just move the node within the same level as its original level, you may set the property EnableFixedDepthDragDrop=true, then the nodes can only be dragged and dropped to the same level as its original level, visit online demo.

23. Add OnNodeDragAndDropStartScript Event

A new event OnNodeDragAndDropStartScript is now available for developers to execute some JS when the end user start to drag nodes. Here’s a usage sample:

Add a property for astreeview:

OnNodeDragAndDropStartScript="dndStartHandler( elem )"

The JS function to handle start drag drop:

//parameter must be "elem" 
functiondndStartHandler( elem ){   
    += (">>drag started. [Node]"+ elem.getAttribute("treeNodeValue")   
    +" [Parent]:"+ elem.parentNode.parentNode.getAttribute("treeNodeValue")   

24. New node type: TextNode

The content of tree nodes is now more flexible. You can add HTML, JavaScript in the new node type – TextNode:



25. Supports Customized JavaScript Handler

For example, if the developer wants to cancel add node action if server returns some specified condition. He can:

  1. Set EnableOnNodeAddedScriptReturn="true"
  2. Set OnNodeAddedScript="addedHandler(elem)"
  3. Write the addedHandler:
    function addedHandler( elem ){
        var message = '';
        var result = true;
        var aTag = elem.getElementsByTagName('A')[0];
        if( aTag.getAttribute('addfailed') == 'true' ){
            alert( aTag.innerHTML );
            return false;
            message = (">>add completed. [Node]" 
            + elem.getAttribute("treeNodeValue") + "<br />" );
        += message;
        return result;

In this case, when the server side returns the node with addfailed in the anchor, the astreeview will cancel the add action.

The same approach can be applied on Edit, Delete and DragDrop.

Some screenshots:



26. New API added (1.5.8)

New API added in 1.5.8:

  • SelectNode – select a node by node value
  • CheckNodes – check nodes by node values
  • UnCheckNodes - uncheck nodes by node values
  • FindByValue – find node by node value, just like the FindControl in WebControl
  • FindByText – find node by node text

27. Enable/Disable feature in ASDropDownTreeView

Developers now can set Enabled property of ASDropDownTreeView to enable/disable it.

The configuration in aspx:

this.astvMyTree.Enabled = false;

28. EnableOpenClose property for ASTreeViewNode

It’s now possible to remove the plus/minus icon in front of the tree node. This is for some situation that some nodes are needed to always be open. Just simply set the EnableOpenClose to false to remove the open/close icon:

someNode.EnableOpenClose = false;

29. [IMPORTANT]Drag and Drop API change in 1.5.8

In the new version, I changed the OnNodeDragAndDropCompleteScript to OnNodeDragAndDropCompletingScript and added a new API called OnNodeDragAndDropCompletedScript.

And the difference between the new APIs:

In OnNodeDragAndDropCompleting, you CANNOT get the new siblings of the current node because the drag and drop hasn’t finished yet. But you can cancel the drag and drop at this time.

In OnNodeDragAndDropCompleted, you CANNOT cancel the drag and drop because the node has been appended to the new node. But at this time, you can get the new parent, new sibling of the current node.

If you are going to update to 1.5.8 and you’re using the on node drag and drop event, please update your code, change the OnNodeDragAndDropComplete to OnNodeDragAndDropCompleting to keep the same behavior.


In order to manage request in a good manner, I setup a mantis system for submitting requests and bugs. Please find the Mantis link in

Points of Interest

I spent two or three months in development, and the ASTreeView is finally finished. Now I would like to introduce it to you. Your feedback is appreciated!


The current version of ASTreeView is 1.5.8, visit for details.

In the release 1.5.8, several new features are added:

  1. New APIs
  2. Enable/Disable feature in ASDropDownTreeView
  3. EnableOpenClose property for ASTreeViewNode
  4. [IMPORTANT] Drag and Drop API change

In the release 1.5.5, several new features are added:

  1. Added new API for check, select and find nodes: SelectNode, CheckNodes, UnCheckNodes, FindByValue, FindByText
  2. Added new node type:TextNode
  3. Added EnableDragDropOnIcon property
  4. Supports customized JavaScript handler
  5. Improved CSS for ASTreeView
  6. Improved ViewState Management
  7. Strong Named Assembly

In the release 1.4.0, several new features are added:

  1. Vertical Drag and Drop Nodes
  2. Fix Drag and Drop depth
  3. Add OnNodeDragAndDropStartScript Event
  4. Several bugs fixed

In the release 1.3.0, several new features are added:

  1. Themes
  2. Right-To-Left support
  3. HTML as TreeNodeText supported
  4. Support escape edit/add input
  5. Multiline Edit Mode supported
  6. Drag and drop complete event now is available
  7. New property for ASTreeViewNode EnableChildren


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


About the Author

JIN Weijie
Software Developer (Senior) Honeywell
China China
ASTreeView, the best FREE treeview control for ASP.NET.

Comments and Discussions

Question.Net 4.0 Pin
smithmrk26-Sep-19 6:37
Membersmithmrk26-Sep-19 6:37 
QuestionASTreeView - DropDown Tree Pin
NandikaMirihana21-May-17 18:41
MemberNandikaMirihana21-May-17 18:41 
QuestionDelete with server side actions Pin
audiogio24-Sep-16 6:56
Memberaudiogio24-Sep-16 6:56 
QuestionHow to use ASTreeView Control ASP.NET Pin
Anil Sharma RCF15-Jul-16 20:43
MemberAnil Sharma RCF15-Jul-16 20:43 
Questiongoldtect.ASTreeView assembly isn't usable Pin
kedigemisi28-Dec-15 20:39
Memberkedigemisi28-Dec-15 20:39 
QuestionASTreeView Client Functionc Pin
Leah Schneider24-Dec-15 3:19
MemberLeah Schneider24-Dec-15 3:19 
GeneralASTreeView - Free ASP.NET TreeView Control Pin
Renuka Ruke21-Jan-15 19:45
MemberRenuka Ruke21-Jan-15 19:45 
QuestionTreeView is rendered in HTML in disabled mode Pin
Member 1105606218-Oct-14 19:41
MemberMember 1105606218-Oct-14 19:41 
QuestionCould you have multiple columns? Pin
Karl Allitt8-Mar-14 7:20
MemberKarl Allitt8-Mar-14 7:20 
AnswerRe: Could you have multiple columns? Pin
JIN Weijie9-Mar-14 15:53
MemberJIN Weijie9-Mar-14 15:53 
GeneralMy vote of 5 Pin
Champion Chen23-Feb-14 3:09
MemberChampion Chen23-Feb-14 3:09 
QuestionNuGet Package Pin
Ciaran Gallagher27-Nov-13 4:01
MemberCiaran Gallagher27-Nov-13 4:01 
AnswerRe: NuGet Package Pin
JIN Weijie27-Nov-13 4:36
MemberJIN Weijie27-Nov-13 4:36 
AnswerRe: NuGet Package Pin
JIN Weijie18-Feb-14 14:37
MemberJIN Weijie18-Feb-14 14:37 
Questioncategory managment Pin
Mostafa Taghipour11-Sep-13 9:09
MemberMostafa Taghipour11-Sep-13 9:09 
QuestionHow to get the astreeview's selectednode depth? Pin
sangsangno124-Jul-13 22:22
Membersangsangno124-Jul-13 22:22 
QuestionHow to change the tree node context menu? Pin
sangsangno122-Jul-13 21:18
Membersangsangno122-Jul-13 21:18 
AnswerRe: How to change the tree node context menu? Pin
JIN Weijie23-Jul-13 1:12
MemberJIN Weijie23-Jul-13 1:12 
QuestionRe: How to change the tree node context menu? Pin
sangsangno123-Jul-13 17:40
Membersangsangno123-Jul-13 17:40 
Question Pin
kktt1-Jul-13 7:36
Memberkktt1-Jul-13 7:36 
BugDropdown text clearing itself after postback in UpdatePanel Pin
n0e10-Jun-13 2:42
Membern0e10-Jun-13 2:42 
QuestionAdd primary key & node name together Pin
ARIA 515-Apr-13 20:56
MemberARIA 515-Apr-13 20:56 
AnswerRe: Add primary key & node name together Pin
JIN Weijie16-Apr-13 2:46
MemberJIN Weijie16-Apr-13 2:46 
QuestionUncheck node by Value in client-side Pin
anguila27-Mar-13 12:57
Memberanguila27-Mar-13 12:57 
AnswerRe: Uncheck node by Value in client-side Pin
JIN Weijie27-Mar-13 14:54
MemberJIN Weijie27-Mar-13 14:54 

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.