Click here to Skip to main content
13,044,467 members (57,679 online)
Rate this:
Please Sign up or sign in to vote.
See more:

I have a listview that has 4 columns e.g.

Surname, Forename, Department, Salary

There are basically 2 things I want to do.

1. When I select say Department, how can I get DEPARTMENT displayed to show what column I selected.
2. What is the best way to sort depending on what column was sorted.

The following code will display all the column names but if I select a specific column, I want as above.

For x As Integer = 0 To MyListView.Columns.Count - 1
Posted 23-Apr-13 4:46am
Updated 24-Apr-13 10:42am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

1. Create a Class that implements IComparer.Compare
See the example in the ListView.ListViewItemSorter property documentation.

2. Set the ListView.ListViewItemSorter[^] property to the IComparer.Compare Class.
You can use this property to provide custom sorting, for example, when a column header is clicked in the details view. To do this, create a class that implements the IComparer interface and provides a constructor that accepts the index of a column to sort by. You can then implement a handler for the ColumnClick event that creates an instance of this class using the index of the clicked column. When you set the ListViewItemSorter property to the new instance, the ListView control is automatically sorted using the specified object. Subsequent calls to the Sort method use the same object.

A tip: Put all of the statements within the IComparer.Compare Class's Compare function within a Try..Catch statement and, after you have debugged the code, Return 0 in the Catch block. In my experience, I had to do this because sometimes the Compare function was called and an error occurred during the Compare function. It has been awhile since I experienced this so I don't remember the exact circumstances but I remember it was when the ListView control was in a state where it shouldn't have been trying to sort the rows. I think it might have been because the Compare function was called when the ListViewItemSorter was set but I am not sure.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170713.1 | Last Updated 24 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100