I want to organize a set of Object (MyPlugin) in a TreeView by Category.
Actually i’m adding them to the TreeView using the following method :
internal static TreeNode AddPluginNode(TreeView parent, AbstractEnvChecker plugin)
{
TreeNode created = new TreeNode(plugin.Name) { Tag = plugin };
parent.Nodes.Add(created);
return created;
}
// I’m using the Tag so i can conserve the MyPlugin Type for each Node
And this is the method i’m using to populate my TreeView from a List<MyPlugin> :
internal static void FillTreeViewWithPlugins(TreeView p_TreeView, Type p_Type, IList<AbstractEnvChecker> p_List)
{
TreeNode v_TreeNode;
if (p_TreeView != null)
{
p_TreeView.Nodes.Clear();
foreach (object p_Item in p_List)
{
if (p_Item.GetType().IsSubclassOf(p_Type))
{
v_TreeNode = null;
v_TreeNode = AddPluginNode(p_TreeView, p_Item as AbstractEnvChecker);
}
}
}
}
Everything works well, but the problem is that the previous method displays a simple TreeView that contains then list of MyPlugin. I want to classify them by a property called Category (String MyPlugin.Category).
So i should proceed like this :
TreeNode testNodeA = new TreeNode("A");
TreeNode testNodeB = new TreeNode("B");
TreeNode testNodeC = new TreeNode("C");
TreeNode[] array = new TreeNode[] { testNodeA, testNodeB, testNodeC };
TreeNode cat = new TreeNode("Categorie X", array);
treeView1.Nodes.Add(cat);
- If i want to keep my previous code, i cannot know how many plugins will i add to each category so i cannot use an
Arraywith fixed dimensions … - I can’t use
Listbecause theTreeNodeconstructor accepts onlyArrayand theTreeView.Nodes.Addmethod accepts onlyTreeNode…
How can i do it ?
Build a dictionary of categories on the fly while creating the nodes. Later, add only these nodes to the tree. The steps are as follows:
Declare a dictionary like that
The key is the category name, the value is the
TreeNodefor the category.While iterating over all the
MyPlugins in your list, check whether there’s a category node in the dictionary and create one if there’s not:Add the new
TreeNodefor the plugin under the respective category node:In the end, add all the values of the dictionary to the tree:
Your code should look like this: