Sort ListViewGroups of a ListView alphabetically

本秂侑毒 提交于 2019-12-11 02:56:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12546968/sort-listviewgroups-of-a-listview-alphabetically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!