How to display a tree structure using ObjectListView or TreeListView

Jeff picture Jeff · Jul 19, 2012 · Viewed 7.8k times · Source

I have been looking into ObjectListView for .NET, and have tried messing with it myself.

I come from using VirtualTreeview with Delphi, so if you could point out the similarities, that would be great!

I tried creating a multilevel tree using TreeListView and the following class:

public class MyClass
{
    public string Name { get; set; }
    public List<MyClass> MyClasses { get; set; }
    public MyClass(string name)
    {
        Name = name;
        MyClasses = new List<MyClass>();
    }
}

The TreeListView is a design-time component. I use this code to create dummy data and have the TreeListView display it.

var MyClasses = new List<MyClass>();
MyClasses.Add(new MyClass("Bob"));
MyClasses.Add(new MyClass("John"));
var myClass = new MyClass("Mike");
myClass.MyClasses.Add(new MyClass("Joe"));
MyClasses.Add(myClass);

treeListView1.SetObjects(MyClasses);

I also have a single column displaying the Name property.

All this works, except that I am not seeing a child-node for the Mike node. I cant seem to figure out what to do here. I looked at the documentation, but couldn't find anything helpful.

Also, can a multilevel structure like this be used with the other variants of ObjectListView, such as FastObjectListView?

Answer

Jeff picture Jeff · Jul 23, 2012

Finally figured it out!

Apparently, the only variant of the ObjectListView suite that can be used for a tree structure by design, is the TreeListView!

Here is how I managed to have my TreeListView display a list of the following class:

public class MyClass
{
    public string Name { get; set; }
    public List<MyClass> MyClasses { get; set; }
    public MyClass(string name)
    {
        Name = name;
        MyClasses = new List<MyClass>();
    }
}

In the Form constructor, we need 2 delegates - one for telling the OLV that an object HAS children, and one for passing the list of children to the OLV.

// model is the currently queried object, we return true or false according to the amount of children we have in our MyClasses List
treeListView1.CanExpandGetter = model => ((MyClass)model).
                                              MyClasses.Count > 0;
// We return the list of MyClasses that shall be considered Children.
treeListView1.ChildrenGetter = delegate(object model)
                                       {
                                           return ((MyClass) model).
                                                   MyClasses;
                                       };

// We also need to tell OLV what objects to display as root nodes
treeListView1.SetObjects(listOfObjects);

I also find it necesary to refresh the parent object whenever I add children to it.