Question : vb.net - sort listview items

hello there,
I have a listview with 3 columns and I am using this code that works but only for column 1..
what can I do so that it can sort the other two columns?
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
Dim xlst As Boolean
    Private Sub lstMain_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles lstMain.ColumnClick
 
        If xlst Then
            lstMain.Sorting = SortOrder.Ascending
            xlst = False
        Else
            lstMain.Sorting = SortOrder.Descending
            xlst = True
        End If
    End Sub

Answer : vb.net - sort listview items

if you want to allow user to sort both ascending and descending then
replace ListViewItemComparer class with following code

and write column_click as following

 Dim f As Boolean = False

  Private Sub ListView1_ColumnClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick
    If f Then
      ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, Windows.Forms.SortOrder.Ascending)
      f = False
    Else
      ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, Windows.Forms.SortOrder.Descending)
      f = True
    End If


  End Sub
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
Class ListViewItemComparer
  Implements IComparer
  Private col As Integer
  Private order As SortOrder 
  Public Sub New()
    col = 0
    order = SortOrder.Ascending
  End Sub 
  Public Sub New(ByVal column As Integer, ByVal order As SortOrder)
    col = column
    Me.order = order
  End Sub 
  Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
                      Implements System.Collections.IComparer.Compare
    Dim returnVal As Integer = -1
    returnVal = [String].Compare(CType(x, _
                    ListViewItem).SubItems(col).Text, _
                    CType(y, ListViewItem).SubItems(col).Text)
    ' Determine whether the sort order is descending.
    If order = SortOrder.Descending Then
      ' Invert the value returned by String.Compare.
      returnVal *= -1
    End If 
    Return returnVal
  End Function
End Class
Random Solutions  
 
programming4us programming4us