views:

132

answers:

2

I have to build a tree using the following data which comes from a DB:

ID          Name     ManagerID
180002      john     180001
180003      Michel   180002
180005      smith    180003

john
 |_Michel
    |_ smith

Specifically, I need to make an ASP.NET TreeView control. The depth of the TreeView is not fixed.

A: 

You didn't specify whether you're using C# or VB, but the approach is the same either way.

You start by creating a TreeNode for every top-level individual (the ones without ManagerIDs, or with a special ManagerID code that indicates top-level).

Then, recursively, for every individual that reports to the current manager, create a new TreeNode and add it as a child for the current manager. Find everyone who reports to him, and apply this function to them. Stop when no one reports to the current person.

So, assuming you have a DataSet with the details of this table, you'd do something like this (VB example):

Sub PopulateTreeNode(
  CurrentNode As TreeNode,
  CurrentManagerID As String,
  Table As DataTable
) As TreeNode
  For Each Row As DataRow In _ 
  DataTable.Select("ManagerID = '" & CurrentManagerID & "'")
    Dim CurrentUser As String = Row("ID").ToString()
    Dim Node As New TreeNode(CurrentUser)
    PopulateTreeNode(Node, CurrentUser, Table)
    CurrentNode.Nodes.Add(Node)
  Next
End Sub
Welbog
Thanks it works is there any to avoid the post back so that the node get selected but it will not post back to the server
muthu
You can wrap it in an UpdatePanel, or you can set the AutoPostBack property of the Tree and its nodes to false.
Welbog
A: 

You mean populating TreeView control with hierarchical data?

You can check this article on ASPAlliance or this on CodeProject.

rafek