5,696,576 members and growing! (16,034 online)
Email Password   helpLost your password?
Desktop Development » List Controls » ListView controls     Intermediate

ListViewSortManager control

By Eddie Velasquez

Add column sorting to the ListView control the easy way.
C#, VC7, C++, Windows, .NET, .NET 1.0, .NET 1.1VS.NET2003, Visual Studio, Dev

Posted: 21 Apr 2002
Updated: 12 Dec 2004
Views: 158,658
Bookmarked: 79 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
67 votes for this Article.
Popularity: 8.53 Rating: 4.67 out of 5
2 votes, 3.2%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
7 votes, 11.3%
4
53 votes, 85.5%
5

Introduction

.NET's ListView control is a nice wrapper around the native List control, but the support for column sorting falls a bit short of what's commonly necessary. Some solutions to this problem require you to derive from a class that implements column sorting however. Since inheritance introduces very tight coupling between components, it is not the appropriate solution in every case. For example, your custom ListView derives from a class that implements functionality that you need except for column sorting and you cannot change the base class.

ListViewSortManager provides several useful features:

  • Easy to use.
  • Case-sensitive (ListViewTextSort) and case-insensitive (ListViewTextCaseInsensitiveSort) text sorting.
  • Integer (ListViewInt32Sort and ListViewInt64Sort) and floating-point (ListViewDoubleSort) sorting.
  • Date (ListViewDateSort) sorting.
  • Extendable for other specialized user-provided sort orders.
  • Transparently handles null and empty strings.
  • Transparently handles ascending and descending orderings.
  • Displays the sort order image in the column headers.
  • The user can specify the column and sort order at any time.
  • Automatic sorting can be disabled for batch insertion of elements to the list.

Usage

  1. Add a variable of type ListViewSortManager.
    private ListViewSortManager m_sortMgr;
  2. In your form's constructor, after the call to InitializeComponent(), construct the ListViewSortManager passing the list and an array of Type for sorters. There should be one entry in the array for each column in your list. The constructor takes care of hooking into the ListView's ColumnClick event.
    public MainForm()
    {
       //
    
       // Required for Windows Form Designer support
    
       //
    
       InitializeComponent();
    
       m_sortMgr = new ListViewSortManager(m_list, 
          new Type[] {
             typeof(ListViewTextSort),
             typeof(ListViewTextCaseInsensitiveSort),
             typeof(ListViewIntegerSort),
             typeof(ListViewFloatSort),
             typeof(ListViewDateSort)
          }
       );
    }
  3. Voilá! Column sorting has been added to your list.

Extended Usage

If you need to provide a sort ordering that doesn't match the ones provided, you just have to derive a class from ListViewTextSort and, override the OnCompare() method which receives two strings that have to be converted to whatever format that your comparison is based on.

public class ListViewDateSort: ListViewTextSort
{
    public ListViewDateSort(int column, bool ascending):
        base(column, ascending)
    {
    }

    protected override int OnCompare(string lhs, string rhs)
    {
        return DateTime.Parse(lhs).CompareTo(DateTime.Parse(rhs));
    }
}

To Do

  • Investigate alternative, more efficient solutions for sorting that don't require text conversions. Probably, using ListView.Tag and adding overridables to ListViewSortManager.
  • As soon as C# implements generics, implement the comparers as templates.

Updates

Version 1.4 (12/11/04)

  • Added the SortEnabled property to enable/disable automatic sorting of the list's elements. Setting SortEnabled to false before adding a large number of elements to the list will speed up the insertion considerably. (Thanks to Jimmy S. for the suggestion.)
  • Added support for native header sort arrows when using version 6 of the Common Controls library. (Thanks to Arlen Feldman for the suggestion.)

Version 1.3 (02/17/03)

  • ShowHeaderIcon() always left-aligned the column header text regardless of the settings. (Thanks to Jezbo for spotting this).
  • ShowHeaderIcon() now locates the sorting arrow icon on the opposite side of the column header text.

Version 1.2 (11/08/02)

  • The ListViewSortManager's constructor now hooks up to the ColumnClick event making it much easier to use the control. (Thanks to debaser for the suggestion).
  • I forgot to set the transparency for the arrow images. (Thanks to Carlo J. Bos and Cory Smith for spotting this).
  • Made Sort() public again and added an overload that allows to select the column and sort order used. Also added Column and SortOrder properties (Thanks to Cory Smith for the suggestion).

Version 1.1 (11/07/02)

  • Implemented ascending/descending arrow images in column headers. No code changes are necessary to benefit from this.

Version 1.0 (04/22/02)

  • Initial release.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Eddie Velasquez



Occupation: Web Developer
Location: United States United States

Other popular List Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 147 (Total in Forum: 147) (Refresh)FirstPrevNext
GeneralA Big Thank You...memberRoland Zerek11:49 28 Jul '08  
GeneralMulticolumn Sorting available! [modified]memberLuis Alonso Ramos11:13 1 Dec '07  
GeneralProblems with native arrowsmemberMockum11:35 30 Jul '07  
GeneralRe: Problems with native arrowsmemberRyan Dunn9:02 18 Apr '08  
QuestionVS2005 bug - arrows don't displaymemberStoj13:24 9 May '07  
AnswerRe: VS2005 bug - arrows don't displaymemberAmro Khasawneh3:44 19 Jun '07  
QuestionProblem when resize column widthmemberwhiteshark200322:48 2 May '07  
GeneralSorting Text with Numbers [modified]memberDeeJRoss12:02 28 Aug '06  
GeneralRe: Sorting Text with NumbersmemberEddie Velasquez12:21 28 Aug '06  
QuestionCopyright?memberdkintgen6:16 2 Aug '06  
AnswerRe: Copyright?memberEddie Velasquez6:21 2 Aug '06  
Generalnulls crash comparermemberCapt'N Stabbin'19:03 17 Jul '06  
GeneralAuto Filter ListViewmemberANIL KUMAR SHARMA (INDIA)0:15 1 Apr '06  
AnswerRe: Auto Filter ListViewmemberCapt'N Stabbin'8:13 17 Jul '06  
GeneralRe: Auto Filter ListView [modified]memberANIL KUMAR SHARMA (INDIA)19:48 17 Jul '06  
GeneralListViewDateSort with date format dd-MM-yyyy doesn't work?memberid10t6:44 30 Mar '06  
GeneralRe: ListViewDateSort with date format dd-MM-yyyy doesn't work?memberPaula Garden17:53 22 Jul '07  
GeneralGood Solutionmembernorm.net23:17 14 Mar '06  
AnswerRe: Good SolutionmemberCapt'N Stabbin'8:18 17 Jul '06  
GeneralConversion To Vb.netmembereatwork7:05 12 Jan '06  
GeneralRe: Conversion To Vb.netmemberDarshon19:37 6 Jun '08  
GeneralRe: Conversion To Vb.netmemberMember 40591412:34 24 Oct '08  
GeneralImageList images overwriting arrowsmemberMilligrant8:38 1 Nov '05  
GeneralColumn without ComparermemberEugene Pankov5:32 6 Sep '05  
GeneralMinor typo in articlememberwout de zeeuw11:08 28 Aug '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Dec 2004
Editor: Smitha Vijayan
Copyright 2002 by Eddie Velasquez
Everything else Copyright © CodeProject, 1999-2008
Web09 | Advertise on the Code Project