Search code examples
c#winformsobjectlistview

ObjectListView how to show child list<>


Hi Im using ObjectListView, and having this classes:

public class Person
{
    public string Name{get;set;}
    public List<Things> {get;set;}
}

public class Things
{
    public string Name{get;set;}
    public string Description{get;set;}
}

How can I show something like this in the ObjectListView:

enter image description here


Solution

  • I believe a tree-view can help here. You could use the TreeListView component which is part of the ObjectListView. It is very similar in use. You have to provide the relevant delegates and the TLV will do the work.

    I built a a quick example:

    enter image description here

    Of course, there is lots of room for customization and improvement.

    public partial class Form2 : Form {
        public Form2() {
            InitializeComponent();
    
            // let the OLV know that a person node can expand 
            this.treeListView.CanExpandGetter = delegate(object rowObject) {
                return (rowObject is Person);
            };
    
            // retrieving the "things" from Person
            this.treeListView.ChildrenGetter = delegate(object rowObject) {
                Person person = rowObject as Person;
                return person.Things;
            };
    
            // column 1 shows name of person
            olvColumn1.AspectGetter = delegate(object rowObject) {
                if (rowObject is Person) {
                    return ((Person)rowObject).Name;
                } else {
                    return "";
                }
            };
    
            // column 2 shows thing information 
            olvColumn2.AspectGetter = delegate(object rowObject) {
                if (rowObject is Thing) {
                    Thing thing = rowObject as Thing;
                    return thing.Name + ": " + thing.Description;
                } else {
                    return "";
                }
            };
    
            // add one root object and expand
            treeListView.AddObject(new Person("Person 1"));
            treeListView.ExpandAll();
        }
    }
    
    public class Person {
        public string Name{get;set;}
        public List<Thing> Things{get;set;}
    
        public Person(string name) {
            Name = name;
            Things = new List<Thing>();
            Things.Add(new Thing("Thing 1", "Description 1"));
            Things.Add(new Thing("Thing 2", "Description 2"));
        }
    }
    
    public class Thing {
        public string Name{get;set;}
        public string Description{get;set;}
    
        public Thing(string name, string desc) {
            Name = name;
            Description = desc;
        }
    }
    

    Inn addition to the provided code, you obviously have to add the TLV to you form and add two columns.