Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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?

  • *Gurus*
Posted

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.

MVP, Visual Developer - .NET

 

Now you see why evil will always triumph - because good is dumb.

 

My free .NET Windows Forms Controls and Articles

Posted
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 :)

Be you his eunuch, and your mute I'll be:

When my tongue blabs, then let mine eyes not see.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...