Saturday, February 5, 2011

Displaying a custom hierarchy.

I have a simple hirachey of Tasks similar to the snipet below:

public class Task
{
    public Guid TaskId { get; set; }
    public Guid ParentId { get; set; }
    public string Name { get; set; }
    public List<Task> Subtasks = new List<Task>();
}

What would be be the best way to display this data? A TreeView would be look ideal but since im not using a DataSet is this control excluded? Or how could i modify my code to enable me to use a TreeView?

Cheers Anthony

  • You do not need to make the TreeView data bound.

    You can create TreeNode instances, and add them to the TreeView.Nodes collection yourself.

    This would allow you to create a TreeView programmatically from your data.

  • Take a look at the TreeView.Nodes.Add method.

    Then use recursion to add the sub tasks. Something like this:

    public void AddTaskToTree(TreeNodeCollection nodes, Task aTask)
    {
        TreeNode taskNode = New TreeNode(aTask.Name);
        nodes.Add(taskNode);
        foreach (Task subTask in aTask.Subtasks)
        {
            AddTaskToTree(taskNode.Nodes, subTask);
        }
    }
    

0 comments:

Post a Comment