如何样将listview按数值大小排序

2024-11-16 18:13:22
推荐回答(2个)
回答1:

Public Class Form1
Dim sortColumn As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i = 0 To 100
ListView1.Items.Add(Int(Rnd() * 10000))
ListView1.Items(i).SubItems.Add(Int(Rnd() * 10000))
ListView1.Items(i).SubItems.Add(Int(Rnd() * 10000))
ListView1.Items(i).SubItems.Add(Int(Rnd() * 10000))
Next
End Sub
Private Sub ListView1_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick
Dim columnsort As New ColumnSort(e.Column)
columnsort.bAscending = (ListView1.Sorting = SortOrder.Ascending)
If columnsort.bAscending Then
ListView1.Sorting = SortOrder.Descending
Else
ListView1.Sorting = SortOrder.Ascending
End If
ListView1.ListViewItemSorter = columnsort
ListView1.ListViewItemSorter = Nothing

End Sub

Public Class ColumnSort : Implements IComparer
Private columnNum As Integer = 0
Public bAscending As Boolean = True
Public Sub New(ByVal column_to_sort As Integer)
columnNum = column_to_sort
End Sub
Private Function CompareInt(ByVal x As Integer, ByVal y As Integer) As Integer
If x > y Then
Return 1
ElseIf x < y Then
Return -1
Else
Return 0
End If
End Function
Public Function Compare(ByVal a As Object, ByVal b As Object) As Integer Implements IComparer.Compare
Dim listItemA As System.Windows.Forms.ListViewItem = DirectCast(a, System.Windows.Forms.ListViewItem)
Dim listItemB As System.Windows.Forms.ListViewItem = DirectCast(b, System.Windows.Forms.ListViewItem)
Dim xText As String = listItemA.SubItems(columnNum).Text
Dim yText As String = listItemB.SubItems(columnNum).Text
Dim xInt As Integer, yInt As Integer

If bAscending Then
If Integer.TryParse(xText, xInt) AndAlso Integer.TryParse(yText, yInt) Then
Return CompareInt(xInt, yInt)
Else
Return [String].Compare(xText, yText)
End If
Else
If Integer.TryParse(xText, xInt) AndAlso Integer.TryParse(yText, yInt) Then
Return -1 * CompareInt(xInt, yInt)
Else
Return -1 * [String].Compare(xText, yText)
End If
End If
End Function
End Class

End Class

回答2:

先把Sorted属性设置为True。SortOrder属性设置为0 lvwAscending 升序, 单击成绩字段,排序。 代码 Private Sub ListView1_ColumnClick (ByVal ColumnHeader as ColumnHeader) ListView1.SortKey=ColumnHeader.Index-1