ASP.NET - Treeview in asp.net with examples

Asked By Aksara L.P on 11-Jul-11 01:36 AM
Treeview in asp.net with examples
Ravi S replied to Aksara L.P on 11-Jul-11 01:41 AM
HI

try this


screenshots


refer links for code
http://www.codeproject.com/KB/webforms/ClientSideTreeView.aspx
http://www.essentialobjects.com/Products/EOWeb/TreeView.aspx
Jitendra Faye replied to Aksara L.P on 11-Jul-11 01:42 AM
Using TreeView you can make Tree structure in your application.

Example = In this example i m filling TreeView with Directory stucture.

For designing directory structure you can use TreeView.

I am giving two solutions.

Solution1: Non Recursive approach:

private static void ListDirectory(TreeView treeView, string path)

{

treeView.Nodes.Clear();

var stack = new Stack<TreeNode>();

var rootDirectory = new DirectoryInfo(path);

var node = new TreeNode(rootDirectory.Name) { Tag = rootDirectory };

stack.Push(node);

while (stack.Count > 0)

{

var currentNode = stack.Pop();

var directoryInfo = (DirectoryInfo)currentNode.Tag;

foreach (var directory in directoryInfo.GetDirectories())

{

var childDirectoryNode = new TreeNode(directory.Name) { Tag = directory };

currentNode.Nodes.Add(childDirectoryNode);

stack.Push(childDirectoryNode);

}

foreach (var file in directoryInfo.GetFiles())

currentNode.Nodes.Add(new TreeNode(file.Name));

}

treeView.Nodes.Add(node);

}

Solution2: Recursive approach:

private void ListDirectory(TreeView treeView, string path)

{

treeView.Nodes.Clear();

var rootDirectoryInfo = new DirectoryInfo(path);

treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));

}

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)

{

var directoryNode = new TreeNode(directoryInfo.Name);

foreach (var directory in directoryInfo.GetDirectories())

directoryNode.Nodes.Add(CreateDirectoryNode(directory));

foreach (var file in directoryInfo.GetFiles())

directoryNode.Nodes.Add(new TreeNode(file.Name));

return directoryNode;

}

fOLLOW THESE SOLUTIONS AND LET ME KNOW.

TSN ... replied to Aksara L.P on 11-Jul-11 01:45 AM
hi..

Working the Code: TreeView Control Example

Create a new web application, and open the Default.aspx page in design view. Locate the TreeView control in the toolbox and drag it onto the form. Here is what it looks like by default:

Click on the small box located in the upper right-hand corner of the control, choose Auto Format, and select Contacts style:

This will update the control to look like the above. There are many pre-defined formats for you to choose from, take a few moments to look at each of them.

The next step is to add a new XML file to the project and create your data file:

<?xml version="1.0" encoding="utf-8" ?>
 
<Contacts>
  <Contact Name="Salman Khalid">
    <Description Value="Phone#, EMail Address, Web-Site">
    </Description>
  </Contact>
  <Contact Name="Salman 2">
    <Description Value="Phone#, EMail Address, Web-Site">
    </Description>
  </Contact>
  <Contact Name="Salman 3">
    <Description Value="Phone#, EMail Address, Web-Site">
    </Description>
  </Contact>

</Contacts>

Switch back to Default.aspx and add an XMLDataSource object to the form. Set its DataFile to the new XML file. Select the TreeViewControl, and set it's DataSourceID to the XMLDataSource object.

Select the DataBindings property and open the TreeView DataBindings Editor. It will automatically have loaded the nodes. Select "Description" and click ADD. Set ValueField to Value. (Note: you can set value field and display field separately. Like for instance, you could display Client Names, but set the node's value equal to their ID.)

Click on Apply and exit the Editor. Switch to the XML file and set some real-time entries, and run the application.

That's all there is to it. Simple and clear... now switch back to the Default.aspx page and open the TreeView DataBindings Editor again. This time add databinding settings for the Contact nodes.

Save and run the application again.

Change the values in the XML file, and refresh your web-page to see the changes in the tree.

Sample project for this tutorial you can download http://www.beansoftware.com/ASP.NET-Tutorials/Examples/TreeView-Control.zip. Also, you can extend common facilities of TreeView control by combining with AJAX and develop really powerful applications.



http://www.beansoftware.com/ASP.NET-Tutorials/Using-TreeView-Control.aspx
Sreekumar P replied to Aksara L.P on 11-Jul-11 02:01 AM

http://www.clientsideasp.deynu.com/jquerytree/JQuery-Tree.aspx

Database Schema
For Asp.Net JQuery Tree you can use the same Asp.Net tree DB schema which I explained in my http://www.clientsideasp.net/2009/03/27/aspnet-tree-dropdownlist-listbox/#more-27Its an N-Level tree and can be stored in a self referencing table (a table with foreign key to the same table). The table will have a PK field ID and an FK field ParentID which will refer to the ID field of same table itself.

Asp.Net Dropdownlist tree DB Schema

Asp.Net Dropdownlist tree DB Schema

Implementation
First select the whole data into a DataTable using the following SELECT query (same as in the case of dropdownlist tree – http://www.clientsideasp.net/2009/03/27/aspnet-tree-dropdownlist-listbox/)

SELECT TreeNodeID
, ISNULL(ParentNodeID, 0) ParentNodeID
, Title
FROM [dbo].[TreeNode] ORDER BY ParentNodeID, TreeNodeID

Now we will recursively create a string with the tree nodes and display in a literal control.


System.Text.StringBuilder tree = new System.Text.StringBuilder();
string previousParentID = "";
int level = -1;
 
private void RecursiveFillTree(DataTable dtParent, string parentID)
{
level++; //on the each call level increment 1
DataView dv = new DataView(dtParent);
dv.RowFilter = string.Format("ParentNodeID = {0}", parentID);
if (dv.Count > 0)
{
//loop through each leaf
for (int i = 0; i < dv.Count; i++)
{
//NEW NODE - make a new Unordered list element
if (previousParentID != dv[i]["ParentNodeID"].ToString())
{
if (level == 0) //START THE TREE
tree.Append("n<ul id='ulTree'>");
else
tree.Append("n<ul>");
}
//show the leaf in an li
tree.Append("n<li><a href='?").Append(dv[i]["TreeNodeID"]).Append("'>").Append(dv[i]["Title"]).Append("</a>");
//recusrively show child leafs of the current leaf
RecursiveFillTree(dtParent, dv[i]["TreeNodeID"].ToString());
previousParentID = dv[i]["ParentNodeID"].ToString();
tree.Append("n</li>");
}
tree.Append("n</ul>");
}
}

http://www.clientsideasp.net/2009/03/31/database-driven-aspnet-jquery-tree/#

The above string will be set to a literal defined in the ASPX page.


<asp:Literal ID="litTree" runat="server"></asp:Literal>


You should refer the javascript files jquery-latest.js, jquery.treeview.js and jquery.cookie.js.
Also include the following JavaScript in the head portion of your ASPX


<script type="text/javascript">
$(function() {
$("#ulTree").treeview({
collapsed: false,
animated: "medium",
persist: "location"
});
})
</script>


ulTree is the ID of ul we have created in C#. I have used three properties available with JQuery tree and you can read the details about all the options available http://www.dynamicdrive.com/dynamicindex1/treeview/index.htm.

http://www.clientsideasp.deynu.com/jquerytree/JQuery-Tree.aspx

http://www.clientsideasp.deynu.com/jquerytree/JQuery-Tree.aspx

http://www.clientsideasp.deynu.com/jquerytree/JQuery-Tree.aspx

Asynchronous Asp.Net JQuery tree

Asynchronous implementation will be very useful when you have very very big tree and if the loading of all the nodes in HTML affect the page load time.

In that case we can show only the root nodes and when some one click the expand button we can send a request to server and load the child nodes for that root node and so on.

The implementation of Asynchronous Asp.Net JQuery tree is very similar to the normal Asp.Net JQuery tree but in this case we will generate a JSON array object having all the node info and write it to the Response.

In the code behind we can get the Asynchronous call by checking the parameter root . If the parameter value is source the Asynchronous request will be for root nodes. And for all the child nodes we will get the ID in root parameter.


public void AsyncTree()
{
string root = Request.Params["root"];
int parentID = 0;
Tree objTree = new Tree();
//select all the nodes - you can make it more efficient by
//storing the datatable Cache to avoid frequent requests to DB
DataTable dtNodes  = objTree.Select(0);
if (root == "source") //for the first time the JQuery tree will send the root param value as "source"
{
GenerateTree(dtNodes, 0);
}
else if (int.TryParse(root, out parentID)) //subsequent requests will send the ID
{
if (parentID > 0)
{
GenerateTree(dtNodes, parentID);
}
}
}
 
private void GenerateTree(DataTable dtParent, int parentID)
{
System.Text.StringBuilder tree = new System.Text.StringBuilder();
DataView dv = new DataView(dtParent);
dv.RowFilter = string.Format("ParentNodeID = {0}", parentID);
tree.Append("[");
//loop through each leaf
for (int i = 0; i < dv.Count; i++)
{
tree.Append("{");
tree.Append(""text": "").Append(dv[i]["Title"]).Append("",");
tree.Append(""id": "").Append(dv[i]["TreeNodeID"]).Append("",");
 
//check whether this node has child nodes
DataView dvChild = new DataView(dtParent);
dvChild.RowFilter = string.Format("ParentNodeID = {0}", dv[i]["TreeNodeID"]);
if (dvChild.Count > 0) //if so mark it in the return node array
tree.Append(""hasChildren": true");
tree.Append("},");
}
//remove the ending comma from the result
if (tree.Length > 1)
{
tree = tree.Remove(tree.Length - 1, 1);
}
tree.Append("]");
//put the result in Response and end the Response
Response.Write(tree.ToString());
Response.End();
}

http://www.clientsideasp.net/2009/03/31/database-driven-aspnet-jquery-tree/#

If a node has child nodes we will set the hasChildren parameter true.
http://www.clientsideasp.deynu.com/jquerytree/JQuery-Tree-Asynch.aspx