Illusion Posted October 21, 2003 Posted October 21, 2003 Hello, I want to sort a listview and am not sure how to go about it, I have read various posts about it and have looked through listviews objects but not sure. Want I want is to click on a column header and it sort by that .. so for example if I have --------- Name | Percent | Time John Smith 78 10:10am Joan Smith 12 12:19pm ----------- When I click on the Percent header, it will sort firstly ASC then if I click again it sorts DESC .. same with Name and Time ... Any Ideas? Quote
*Gurus* divil Posted October 21, 2003 *Gurus* Posted October 21, 2003 The best way of sorting listview is with a ListViewItemComparer. Create yourself a class that implements IComparer. Give it a constructor that takes a column index and a boolean value indicating whether to sort in reverse. The key method to implement is Compare, which passed two values x and y. These will always be strings in the case of the listview. The simplest way to compare them is therefore a string compare, in which case you can just return String.Compare((string)x, (string) y), obviously negating that if you're sorting in reverse. If you know which column you are sorting (you should) you can use more advanced comparers, like DateTime.Compare etc. To apply your sorter to a column, use code like thisin the ColumnClick event: myListView.ListViewItemSorter = new MySorter(e.Column, false); myListView.Sort; It's up to you to record whether the current column is being sorted in reverse order and to adjust the second parameter accordingly. Quote MVP, Visual Developer - .NET Now you see why evil will always triumph - because good is dumb. My free .NET Windows Forms Controls and Articles
pcPirate Posted October 24, 2003 Posted October 24, 2003 Actually, divil is correct, the best way of sorting listview is with a ListViewItemComparer. If you're found it's difficult to create it yourself, you might be interest to download the sample sourcecode from thecodeproject.com . I myself downloaded it and 100% that you'll like it :) Quote Be you his eunuch, and your mute I'll be: When my tongue blabs, then let mine eyes not see.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.