Search code examples
c#winformssortinggroupingobjectlistview

How to Group and Sort Objects in ObjectListView?


I am trying to group my list of objects in an ObjectListView.

The ObjectListView should group the objects based on the first column but then have that same column sorted based on a custom sort.

How do I do that? I have read through the documentation for ObjectListView: http://objectlistview.sourceforge.net/cs/gettingStarted.html#gettingstarted

So far, I have implemented my custom sort but I am not sure how to trigger the grouping? Remember that I am trying to group on the first column but then apply a custom sort.

My custom sort relis on the BeforeSorting event:

// after initializing components
olv.BeforeSorting += olv_BeforeSorting;

Then...

private void olv_BeforeSorting(object sender,BrightIdeasSoftware.BeforeSortingEventArgs e)
{
        olvDataSource.Sort((x, y) => x.Group.ID.CompareTo(y.Group.ID));
        e.Handled = true;
}

The ObjectListView displays my ordered object list but it is not grouped together. Each object displays on its own row without a group heading.

How do I group my objects after sorting them?


Solution

  • I am sharing this for anyone that might come across here looking for a way to apply a custom sort on groups within an ObjectListView.

    There might be better ways to do this, but this way worked for me.

    colFirst.GroupFormatter = (BrightIdeasSoftware.OLVGroup group, BrightIdeasSoftware.GroupingParameters parms) =>
    {
        ObjectA a = (OjectA)group.Key;
    
        /* Add any processing code that you need */
    
        group.Task = " . . . ";
        group.Header = "Special Name: " + a.Name;
        group.Subtitle = $("Object A: {a.Index}, Total Water Consumption: {a.WaterConsumption}");
    
        // This is what is going to be used as a comparable in the GroupComparer below
        group.Id = a.ID;
    
        // This will create the iComparer that is needed to create the custom sorting of the groups
        parms.GroupComparer = Comparer<BrightIdeasSoftware.OLVGroup>.Create((x, y) => (x.GroupId.CompareTo(y.GroupId)));
    };
    

    The OLVColumn.GroupFormatter is lightly explained here: http://objectlistview.sourceforge.net/cs/recipes.html#how-do-i-put-an-image-next-to-a-group-heading