Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting A ListView By Column

Tags:

Currently I use a custom sorter on the listview, and i can sort the listview each time i click on the FIRST column, but it won't sort by other columns.

SortStyle: Variable to determine whether it is Ascending Sort, or Descending.

if (e.Column == 0) {     if (SortStyle == 0)     {         List.ListViewItemSorter = customSortDsc;         SortStyle = 1;     }     else     {         List.ListViewItemSorter = customSortAsc;         SortStyle = 0;     } } 

This works fine when sorting for the first column, but if you were to do it on any other column, it would just sort by the first column. Is there a way to sort by the column clicked?

like image 209
Mike Avatar asked Oct 10 '09 16:10

Mike


People also ask

How do you sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.


2 Answers

Forget about your custom sorter. Start over using the code at the following page. It will show you how to define a class that inherits from the IComparer interface. Each line is commented out, so you can actually see what is happening. The only potential complication is how you are retrieving your Listview Items from your Listview control. Get those squared away and all you need to do is copy and paste the IComparer interface class and the columnClick method.

http://support.microsoft.com/kb/319401

like image 164
RedEye Avatar answered Sep 28 '22 03:09

RedEye


If you are starting out with a ListView, do yourself a huge favour and use an ObjectListView instead. ObjectListView is an open source wrapper around .NET WinForms ListView, which makes the ListView much easier to use and solves lots of common problems for you. Sorting by column click is one of the many things it handles for you automatically.

Seriously, you will never regret using an ObjectListView instead of a normal ListView.

  • ObjectListView Home Page
  • ObjectListView Nuget Package
like image 25
Grammarian Avatar answered Sep 28 '22 04:09

Grammarian