Sortable ListView


The Windows Forms ListView control doesn’t provide column sorting functionality. So if you click on a column in a ListView Details view, don’t expect the items to be sorted by the clicked column. To get this functionality, we’ll need to sort the items by the clicked column in the ListView ColumnClick event. I searched online for “Sortable ListView” and I found three MSDN articles talking about this: Sort ListView Column in Visual C#, Sorting ListView Items by Column Using Windows Forms, and How to: Sort ListView Items. None of those implementations takes into consideration the type of the column being sorted. That is, they all do string sorting. If you have dates and numbers in your list, then they’ll not be sorted properly. For example, number 2 will be considered greater than 11. Date time 9/9/1400 will be considered greater than 11/11/2020. Below is an implementation that takes into consideration string, DateTime, int and double types. It can be easily extended to handle more types.

  • Add the SortableListView control to your Windows Form
  • When adding columns to the SortableListView, set the Tag attribute to the type of the column.
sortableListView.Columns.Add("String Field").Tag = typeof(string);
sortableListView.Columns.Add("DateTime Field").Tag = typeof(DateTime);
sortableListView.Columns.Add("Int Field").Tag = typeof(int);
sortableListView.Columns.Add("Double Field").Tag = typeof(double);
  • Now, you can add the items as usual.

For example, the below list is sorted by the DateTime field.

Sortable ListView

Sortable ListView

 Click on the above image to download the SortableListView control.

About these ads
  1. Great article and a really nice control. Just one question…. why didn’t you add a new Property of, say, ColumnType? I mean this could let the tag property to be used for other purposes….

    Anyways….thank you very much for the control….its really really awesome…

    • My mistake…..Sorry

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: