Being that the free .Net TreeView control does not implement a built in recursion method where you can simply bind a datasource structured like I mention above to it, we have to add child nodes of parent node at runtime. Assuming you are in the same boat as I am/was.
So using that data structure above. I simple placed a TreeView control on the page (*with some simple styles of course)
I then create the recursive method that does the work.
protected void GetKids(TreeNode parentNode, string parentid, DataTable srcTable)
{
DataRow[] dr = srcTable.Select("org_parent_id=" + parentid);
foreach(DataRow cr in dr)
{
TreeNode newnode = new TreeNode();
newnode.Text = cr["org_name"].ToString();
newnode.Value = cr["org_id"].ToString();
parentNode.ChildNodes.Add(newnode);
GetKids(newnode, cr["org_id"].ToString(), srcTable);
}
}
This method takes in the parentNode object, the parentid as a string from that table structure I mentioned above and the datatable which has all the source data in it. Note the last line in this method is a call to itself passing in the id and node of the record currently being processed.
On the Page_Load, I simply then do this...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BusinessObject.DataClasses.Organization Organization = new BusinessObject.DataClasses.Organization();
DataTable dt = Organization.GetOrgStructure(); //Get the org structure table here
DataRow[] dr = dt.Select();
TreeNode tr = new TreeNode();
tr.Text = "Company"; //Top Level Org Unit
tr.Value = "16"; //ID of Top Level Org Unit
tvOrg.Nodes.Add(tr);
GetKids(tr, "16", dt);
}
}
I'm sure this even could be simplified, streamlined and cut down on resources further. I found no samples on the net like this, but was able to think it up in just a few minutes after putting my head on...
