Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

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.

VB
For x As Integer = 0 To MyListView.Columns.Count - 1
       Debug.Print(MyListView.Columns(x).Text)
Next
Posted
Updated 24-Apr-13 10:42am
v4

1 solution

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.
Quote:
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.
 
Share this answer
 
v3

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900