Search code examples
.netwinformslistviewsortingalphabetical

Sort ListViewGroups of a ListView alphabetically


Is it possible to sort all ListViewGroups of a Windows Forms ListView alphabetically at runtime?

Or do I have to manually implement sorting when I'm adding a group (using the "Insert" method of the ListViewGroupCollection)? If this is the case, can someone give me an idea how to do this?


Solution

  • In WinForms ListView, you have to do the sorting manually:

    ListViewGroup[] groups = new ListViewGroup[this.listView1.Groups.Count];
    
    this.listView1.Groups.CopyTo(groups, 0);
    
    Array.Sort(groups, new GroupComparer());
    
    this.listView1.BeginUpdate();
    this.listView1.Groups.Clear();
    this.listView1.Groups.AddRange(groups);
    this.listView1.EndUpdate();
    
    ...
    
    class GroupComparer : IComparer
    {
        public int Compare(object objA, object objB)
        {
            return ((ListViewGroup)objA).Header.CompareTo(((ListViewGroup)objB).Header);
        }
    }
    

    Groups in .NET ListView are quite nasty - they look and behave like a mix between old Win32 ListView and Windows Explorer...

    So I would recommend you Better ListView component which supports sorting groups out of the box:

    this.betterListView1.Groups.Sort(new GroupComparer());
    
    ...
    
    class GroupComparer : IComparer<BetterListViewGroup>
    {
        public int Compare(BetterListViewGroup groupA, BetterListViewGroup groupB)
        {
            return groupA.Header.CompareTo(groupB.Header);
        }
    }
    

    Furthermore, the groups look and behave just like in Windows Explorer, are collapsible and no flickering happens even when you sort them.