Anthony Nichols
Anthony Nichols

Reputation: 1668

Dynamically Generate WinForms TreeView from Assembly

I've almost got it, but I am having a hard time with doing the last part gracefully. This answer was update based on the answer submitted by Jeremy Thompson. This is what I have so far:

public void SetupTree()
{
    var types = Assembly.Load("Data").GetTypes().Where(t => t.IsPublic && t.IsClass);

    if (types.Count() > 0)
    {
        if (treeView_left.Nodes.Count == 0)
        {
            treeView_left.Nodes.Add(new TreeNode("Structure Data"));
            treeView_left.Nodes[0].Nodes.Add(types.First().GetHashCode().ToString(), types.First().Name);
        }

        foreach (Type type in types)
        {
            BuildTree(types, type, treeView_left.Nodes[0].Nodes[0]);
        }
    }

    treeView_left.Refresh();
}

private void BuildTree(IEnumerable<Type> types, Type type, TreeNode parentNode)
{
    var tempNodes = treeView_left.Nodes.Find(type.BaseType.GetHashCode().ToString(), true);
    if (tempNodes.Count() > 0)
    {
        parentNode = tempNodes[0];
        if (tempNodes.Count() != 1)
        {
            //TODO: warning
        }
    }

    if (parentNode != null)
    {
        if (treeView_left.Nodes.Find(type.GetHashCode().ToString(), true).Count() == 0)
        {
            parentNode.Nodes.Add(type.GetHashCode().ToString(), type.Name);
        }

        foreach (Type t in types.Where(x => x.IsSubclassOf(type)))
        {
            BuildTree(types, t, parentNode.Nodes[type.GetHashCode().ToString()]);
        }
    }
}

This produces the result I am looking for, but I suspect I am doing some of this the hardway. If anyone could point out a cleaner method for the last part I would appriciate it.

Upvotes: 2

Views: 1335

Answers (1)

Jeremy Thompson
Jeremy Thompson

Reputation: 65682

I haven't tested this yet, but notice the Recursive call LoadAllChildren calls itself.

public void SetupTree()
{
    Assembly dataLib = Assembly.Load("Data");
    TreeNode theTree = new TreeNode("Assembly Data");

    foreach (Type type in dataLib.GetTypes())
    {
        LoadAllChildren(dataLib, type, theTree);
    }

    treeView_left.Nodes.Add(theTree);  //Optimisation - bind all nodes in one go rather than adding individually
}

private void LoadAllChildren(Assembly dataLib,Type type, TreeNode parentNode)
{
    if (type.IsPublic && type.IsClass)
    {            
        TreeNode node = new TreeNode(type.Name);
        parentNode.Nodes.Add(node);           

        var types = dataLib.GetTypes().Where(x => x.IsSubclassOf(type));
        foreach (Type t in types)
        {
            LoadAllChildren(dataLib, t, node);
        }
    }
}

I hope this is enough to get you over the hurdle, feel free to ask Q's

I wont respond quickly as my PC is about to get rebuilt:(

Upvotes: 1

Related Questions