Search code examples
c#objectlistview

Adding a row of data to ObjectListView


I'm trying for the first time (after many attempts) to get an array of string into a row of ObjectListView in C#. I'm getting no errors but when I compile, all I get is a result row with null in the first column. I am switching over from the basic ListView for the extra functionality of ObjectListView.

 string[] info2 = new string[8] {fileCountSt, fileName, fileExt, fileSize, creator, dateCreated, lastAccessed, filePath};

this.objectListView_FindFiles.SetObjects(info2);

The ObjectListView is setup with 8 columns. I have followed the various tutorials but they involve a lot of unnecessary waffle and code. All I am looking for is to assign some strings into a string array and assign it to the ObjectListView dynamically.

Thanks.


Solution

  • You are not using the right approach. The basic idea is to populate the OLV with objects from a class that represents/contains your data. There are two basic ways to populate the columns of the OLV from a given object.

    1. Configure each columns `AspectName" to the property name of your object that the OLV should use to access the value for that column.
    2. Use the columns AspectGetter property to attach an AspectGetterDelegate that extracts the value to be displayed in that column (this approach allows customization).

    So in your case you wouldn't use a string array, but create a class that holds your information like this for example:

    class FileInfo {
        public string Name { get; set; }
        public string Ext { get; set; }
        public int Size { get; set; }
        public DateTime Created { get; set; }
    
        public FileInfo(string name, string ext, int size, DateTime created) {
            Name = name;
            Ext = ext;
            Size = size;
            Created = created;
        }
    }
    

    And then configure your columns in the designer by setting the AspectName for the first column to "Name", the second to "Ext", third to "Size" and so on...

    Note that you don't have to use properties of type string. The OLV will convert all types to their basic string representation. This can be customized by setting a format string for the AspectToStringFormat property.

    If everything is set up, just add your FileInfo objects using the SetObjects() method.

    List<FileInfo> fInfos = new List<FileInfo>();
    fInfos.Add(new FileInfo("file1", "doc", 1234, new DateTime(2014, 04, 13)));
    fInfos.Add(new FileInfo("file2", "doc", 5678, new DateTime(2014, 04, 14)));
    objectListView1.SetObjects(fInfos);