Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Using the ListView.ListViewItemSorter property - .Net Framework

RSS
Modified on Tue, Oct 28, 2008, 3:16 PM by Administrator Categorized as ┬ĚNet Framework
The following C# code demonstrates how to use the ListViewItemSorter property of the ListView control to sort the contents of a folder containing both subfolders and files. You can convert code between C# and VB.NET at this website.

...

uxMyListView.ListViewItemSorter 
    = (System.Collections.IComparer)(new FolderItemSorter());

...

public class FolderItem
{
    public string Name;
    public bool IsFolder;
    public FolderItem(string name, bool isFolder)
    {
        Name = name;
        IsFolder = isFolder;
    }
}
public class FolderItemSorter : IComparer
{
    int IComparer.Compare(object a, object b)
    {
        int result;
        FolderItem x = (FolderItem)(((ListViewItem)(a)).Tag);
        FolderItem y = (FolderItem)(((ListViewItem)(b)).Tag);
        int flag = (x.IsFolder ? 1 : 0) + (y.IsFolder ? 2 : 0);

        switch (flag)
        {
            //- Neither item is a folder => Compare names
            case 0: result = x.Name.CompareTo(y.Name); break;

            //- A is a folder, but B isn't => A < B
            case 1: result = -1; break;

            //- B is a folder, but A isn't => A > B
            case 2: result = 1; break;

            //- Both items are folders => Compare names
            case 3: result = x.Name.CompareTo(y.Name); break;

            //- Failsafe
            default: result = 0; break;
        }
        return result;

    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.