How to Sort in ListView

venkatarajan

New member
Joined
Jul 15, 2004
Messages
1
Programming Experience
1-3
Hai Friends,
I'm using ListView in My project. I want to Sort on any columns in the ListView.
When I use the Sorting Property, it sorts only based on First Column.
When I use the
ListViewItemComparer Class, it sorts any columns, but gives only in Ascending. But I need to sort Descending also based on any column clicked.

Please help me guys.
I'm in Due Date

Venkatarajan

 
Last edited:

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,321
Location
Sydney, Australia
Programming Experience
10+
Don't know if this is the best way but this is how I do it.

1. In the form containing the listview declare an array as many elements as the listview has columns:

Private sortOrders as SortOrder() = {SortOrder.Ascending, ...}

2. Create your comparing class:

Private Class ListViewSorter
Implements IComparer

Private columnIndex As Integer
Private sortOrder As SortOrder

Public Sub New(ByVal columnIndex As Integer, ByVal sortOrder As SortOrder)
Me.columnIndex = columnIndex
Me.sortOrder = sortOrder
End Sub 'New(Integer)

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
If Me.sortOrder = sortOrder.None Then
Return 0
End If

Dim itemX As ListViewItem = CType(x, ListViewItem)
Dim itemY As ListViewItem = CType(y, ListViewItem)

If Me.sortOrder = sortOrder.Ascending Then
Return String.Compare(itemX.SubItems(columnIndex).Text, itemY.SubItems(columnIndex).Text)
Else
Return String.Compare(itemY.SubItems(columnIndex).Text, itemX.SubItems(columnIndex).Text)
End If
End Function 'Compare()
End Class 'ListViewSorter

3. Finally, declare your event handler for the ColumnClick.

Private Sub listView_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles listView.ColumnClick
Me.listView.ListViewItemSorter = New ListViewSorter(e.Column, columnSortOrders(e.Column))

If columnSortOrders(e.Column) = SortOrder.Ascending Then
columnSortOrders(e.Column) = SortOrder.Descending
Else
columnSortOrders(e.Column) = SortOrder.Ascending
End If
End Sub 'listView_ColumnClick()
 

jimmajsterski

Well-known member
Joined
Oct 29, 2004
Messages
53
Location
Houston, TX, USA
Programming Experience
10+
jmcilhinney- your code works great!
In the listView_ColumnClick sub I added an If, so that a candidate column with sortorder.None will force exit from sub. Otherwise it becomes ascending by your else statement.
Thanks
 
Last edited:
Top Bottom