Search code examples
c#asp.nettreeviewthreaded-comments

How to build an ASP.NET TreeView From Scratch...?


I am trying to build a nested/threaded comment system in ASP.NET. I don't know how the PHP guys do it. Its much harder than first imagined.

I am trying my damnedest get Hierarchical data to output to the user, but its not working.

I have a table with text, a itemID and a parentID.

I want to display the information in a tree view format, but asp.net's standard control just doesn't work...

Can anyone point me in the right direction of how to output this into a treeview. I have tried nesting repeaters, straight out html building from codebehind and the treeview control.

I still haven't found a solution... Can anyone help me out?


Solution

  • Quickly, by head (could not check in VS2k8 now), I would do it something like this using Linq to SQL

    private void BuildTree()
    {
       List<Item> items = from item in dataContext.Items
                          select item;
    
       List<Item> rootItems = items.FindAll(p => p.ParentID == null );
    
       foreach ( Item item in rootItems )
       {
          TreeViewNode tvi = new TreeViewNode(item.text);
          BuildChildNodes(tvi, items, item.ID);
          YourTreeNodeName.Nodes.Add(tvi);
       }   
    }
    
    private void BuildChildNodes(TreeViewNode parentNode, List<Item> items, long parentID)
    {
       List<Item> children = items.FindAll ( p => p.ParentID = parentID );
       foreach( Item item in children)
       {
          TreeViewNode tvi = new TreeViewNode(item.text);
          parentNode.Nodes.Add(tvi);
          BuildChildNodes(tvi, items, item.ID);         
       }
    }