0

after tweaking my code for a bit I ended up with this little proof of concept code:

private void button1_Click(object sender, EventArgs e)
{            
    DepartmentRepository repo = new DepartmentRepository();
    var entries = repo.FindAllDepartments(); //Returns IQueryable<Department>

    treeView1.BeginUpdate();
    var parentDepartments = entries.Where(d => d.IDParentDepartment == null).ToList();
    foreach (var parent in parentDepartments)
    {
        TreeNode node = new TreeNode(parent.Name);
        treeView1.Nodes.Add(node);

        var children = entries.Where(x => x.IDParentDepartment == parent.ID).ToList();
        foreach (var child in children)
        {
            node.Nodes.Add(child.Name);
        }
    }

    treeView1.EndUpdate();
}

It places every parent Department in the TreeView control and then correctly assigns it's children to the correct Parent.

My problem is, how do I handle children of children? Nested Departments.

I can't seem to wrap my head around it.

Thanks for any guidance.

  • possible duplicate of [Can this code be more effecient?](http://stackoverflow.com/questions/4069193/can-this-code-be-more-effecient) – John Hartsock Nov 01 '10 at 14:05
  • Not really; there I was asking about the code/linq usage efficiency. Here I'm asking about how I would access nested departments. –  Nov 01 '10 at 14:29
  • And you should see the debate that has started :) – Bronumski Nov 01 '10 at 17:05

1 Answers1

2

You need to use recursion:

  void LoadNode(TreeNode node, Department d)
  {
     foreach (var child in d.Children)        
     {            
           TreeNode childNode = node.Nodes.Add(child.Name);
           LoadNode(childNode, child); // calls the method again for the next level

     }

  }

Have a look here for sample of recursion: http://www.codeproject.com/KB/cs/recursionincsharp.aspx

Aliostad
  • 80,612
  • 21
  • 160
  • 208