Article C0010 C# .NET
Improved ListView ColumnSort

For one of my projects I needed to sort a ListView by clicking its column. Most of the ListView items were text, but one column contained the DateTime format. I started searching MSDN and found an article from Shannon Dunn of Microsoft. You can visit the original link here.

Strange enough I found the following snippet very odd:

// Try to sort based an a date
try
{
System.DateTime firstDate =
    System.DateTime.Parse(listviewX.SubItems[ColumnToSort].Text);
System.DateTime secondDate =
    System.DateTime.Parse(listviewY.SubItems[ColumnToSort].Text);
compareResult = System.DateTime.Compare(firstDate, secondDate);
}
catch
{
// Compare the two items
compareResult =
    ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,
        listviewY.SubItems[ColumnToSort].Text);
}
In one of my Microsoft Press books I found the design recommendation not to (mis)use the try and catch statement to change the program flow. Furthermore, when I loaded my ListView with 6000 records it took ages prior being responsive again. Each ListView item is challenged against the .Parse and most of them will generate an exception error.

When you use the .NET Framework version 2.0 or higher, you can change .Parse into .TryParse, which prohibit the exception to occur. The improved code will look like this:

System.DateTime fDate = new System.DateTime();
System.DateTime sDate = new System.DateTime();
if (System.DateTime.TryParse(listviewY.SubItems[ColumnToSort].Text, out fDate) &&
    System.DateTime.TryParse(listviewX.SubItems[ColumnToSort].Text, out sDate))
    {
	    compareResult = System.DateTime.Compare(fDate, sDate);
    }
else
    compareResult =
        ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text,
	        listviewY.SubItems[ColumnToSort].Text);
Another performance improvement can be achieved by implementing a SortOrder of None, which allows you to (temporarily) stop the ordering process.

Source code
The source code of the improved example can be downloaded here.

~Edward