单击ListView列标题实现项排序功能:
说明:ListView1是一个ListView,添加ColumnClick事件处理函数ListView1_ColumnClick
Private Sub ListView1_ColumnClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick
If ListView1.Sorting = SortOrder.Ascending Then
ListView1.Sorting = SortOrder.Descending
Else
ListView1.Sorting = SortOrder.Ascending
End If
Me.ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, ListView1.Sorting)
End Sub
Class ListViewItemComparer
Implements IComparer
Private col As Integer
Private sor As SortOrder
Public Sub New()
col = 0
End Sub
Public Sub New(ByVal column As Integer, ByVal sort As SortOrder)
col = column
sor = sort
End Sub
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements IComparer.Compare
If sor = SortOrder.Ascending Then
If col = 0 Then
Return Integer.Parse(CType(x, ListViewItem).SubItems(col).Text) - Integer.Parse(CType(y, ListViewItem).SubItems(col).Text)
Else
Return [String].Compare(CType(x, ListViewItem).SubItems(col).Text, CType(y, ListViewItem).SubItems(col).Text)
End If
Else
If col = 0 Then
Return Integer.Parse(CType(y, ListViewItem).SubItems(col).Text) - Integer.Parse(CType(x, ListViewItem).SubItems(col).Text)
Else
Return [String].Compare(CType(y, ListViewItem).SubItems(col).Text, CType(x, ListViewItem).SubItems(col).Text)
End If
End If
End Function
End Class
本文作者:朱二 来源:http://blog.csdn.net/netcoder/
CIO之家 www.ciozj.com 微信公众号:imciow