How to populate a treeview from a list of objects
c#, list, object, treeview, winforms
Solution
Worked very well, thanks. I've just added a few lines at the beginning and at the end of the else as below.
private void PopulateTreeView()
{
ListOfObjectsSorted = ListOfObjects.OrderBy(r => r.Group).ToList();
var topNode = new TreeNode("Select all");
treeView1.Nodes.Add(topNode);
string currentGroup = ListOfObjectsSorted.First().Group;
var treeNodes = new List<TreeNode>();
var childNodes = new List<TreeNode>();
foreach (Object obj in ListOfObjectsSorted )
{
if (currentGroup == rule.Group)
childNodes.Add(new TreeNode(obj.Name));
else
{
if (childNodes.Count > 0)
{
treeNodes.Add(new TreeNode(currentGroup, childNodes.ToArray()));
childNodes = new List<TreeNode>();
}
childNodes.Add(new TreeNode(obj.Name));
currentGroup = obj.Group;
}
}
if (childNodes.Count > 0)
{
treeNodes.Add(new TreeNode(currentGroup, childNodes.ToArray()));
}
treeView1.Nodes[0].Nodes.AddRange(treeNodes.ToArray());
}
Problem
I'm having a problem populating my treeview from my list of objects. I've been looking for solutions on google, I found some topic close to my problem, but none of them solved it. I have a List with properties for each object : Name and Group. I would like to populate my treeview like below : ``` +---Group 1 | | | +--------object.Name <-- | +--------object.Name <-- all objects with object.Group = Group 1 | +--------object.Name <-- | +---Group 2 | | | +--------object.Name <-- | +--------object.Name <-- all objects with object.Group = Group 2 | +--------object.Name <-- | ``` and so on. Thanks.