Robert said:
Hi there! I've been looking around with little luck on how to populate a
treeview from a single table parent-child relationship. It is simply a
table of users, where each are identified with a unique UserId and have a
corresponding ParentId (pointing to their boss' UserId). If it's a
top-level user, then the ParentId is set to 0. Can someone please help me
figure out the best way to populate this list? I'm unsure of how to do the
logic behind the algorithm. Any help would be greatly appreciated.
It's pretty simple: (I assume your data is in a datatable)
TreeNode rootNode = null;
Hashtable idToNode = new Hashtable(users.Rows.Count);
// first walk the list of users and create Treeview Nodes.
// we need 2 loops, as we can encounter a user with a parent
// and the parent isn't processed yet.
for(int i=0;i<users.Rows.Count;i++)
{
TreeNode newNode = new TreeNode(users.Rows
["UserId"].ToString());
idToNode.Add(users.Rows["UserId"], newNode);
if((int)users.Rows["ParentId"]==0)
{
// found the root
rootNode = newNode;
}
}
// now we're going to build the tree!
for(int i=0;i<users.Rows.Count;i++)
{
TreeNode nodeToAdd = (TreeNode)idToNode[users.Rows["UserId"]];
// find parent
if((int)users.Rows["ParentId"]!=0)
{
TreeNode parentNode = (TreeNode)idToNode[users.Rows["ParentId"]];
parentNode.Nodes.Add(nodeToAdd);
}
}
// add the complete node structure to the treeview control
myTreeView.Nodes.Add(rootNode);
voila, an O(2) algo. This is from my bare head, so I might have made a syntax
error here and there, but you get the idea.
FB