ListView – Sorting by Number or Date

ListView – Sorting by Number or Date

The ListView control that comes with MSCOMCTL.OCX isn’t too bad. It supplies us with most of the things that we need, and makes them incredibly easy to code. As a VC++ developer I can tell you that most of the features that we all take for granted can be a real pig to implement using the MFC and API calls.

One thing that this control is sadly lacking in, however, is the ability to sort by number or date. It would also appear to be something that a lot of people are asking for.

My first attempt at implementing this involved using APIs to talk directly to the ListView window. It was fast and did just the job that I wanted. It did, however, have one major drawback – Microsoft, in their infinite wisdom, have given VB developers a wrapper for the ListView window which stores its own internal collection of listitem data, rather than referencing the window’s own data. The result of this is not only that two copies of the data are stored in memory (Bloatware? It gets my vote…), but if you try to manipulate the listview directly, then all the VB collections go out of synch with what’s displayed on-screen. BIG problem!

For my second attempt, I decided to take a step back, and try something simpler. I decided to make use of the alphabetical sort that has been implemented with the control. It involves locking the window so that no changes in the data are reflected on-screen, re-formatting the list items so that they may be sorted alphabetically, sorting them, and then restoring the original data before unlocking and refreshing the ListView. I know that this is a pig of a way to do things, but it works!

The good news it that the sort is surprisingly fast. On my machine (a PII 350 with 64Mb RAM running NT4), sorting by number takes about 0.4 milliseconds per listitem (when running in the IDE), and by date takes around 0.35ms.

This certainly isn’t THE way to sort ListItems by number or date, but it’ll me do until Microsoft supply a custom sort for the ListView control.

Download Zipped Project File (4k)

Screen shot

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read