在winform中,如何将排序列功能添加到listview列中?

时间:2014-07-04 09:41:37

标签: .net vb.net winforms listview sorting

在winform中,如何将排序列功能添加到listview列中?

我找不到允许> 谢谢

的列的任何适当性

1 个答案:

答案 0 :(得分:2)

您必须编写自己的类来实现IComparer

然后编写一个在此类中实现IComparer.Compare的Compare方法。

以下是我前段时间写过的一个例子,按数字,日期或字符串排序,但你可以修改它以供自己使用:

Public Class ListViewComparer
    Implements IComparer

    Private _columnNumber As Integer
    Private _sortOrder As SortOrder

    Public Sub New(ByVal colIndex As Integer, ByVal sortingOrder As SortOrder)
        _columnNumber = colIndex
        _sortOrder = sortingOrder
    End Sub

    ' Compare the items in the appropriate column
    ' for objects x and y.
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim itemX As ListViewItem = DirectCast(x, ListViewItem)
        Dim itemY As ListViewItem = DirectCast(y, ListViewItem)
        Dim stringX As String = "", stringY As String = ""
        ' Get the sub-item values.

        If itemX.SubItems.Count > _columnNumber Then stringX = itemX.SubItems(_columnNumber).Text
        If itemY.SubItems.Count > _columnNumber Then stringY = itemY.SubItems(_columnNumber).Text

        ' Compare them.
        If _sortOrder = SortOrder.Ascending Then
            If IsNumeric(stringX) And IsNumeric(stringY) Then
                Return CInt(stringX).CompareTo(CInt(stringY))
            ElseIf IsDate(stringX) And IsDate(stringY) Then
                Return DateTime.Parse(stringX).CompareTo(DateTime.Parse(stringY))
            Else
                Return String.Compare(stringX, stringY)
            End If
        Else
            If IsNumeric(stringX) And IsNumeric(stringY) Then
                Return CInt(stringY).CompareTo(CInt(stringX))
            ElseIf IsDate(stringX) And IsDate(stringY) Then
                Return DateTime.Parse(stringY).CompareTo(DateTime.Parse(stringX))
            Else
                Return String.Compare(stringY, stringX)
            End If
        End If
    End Function
End Class

用法:

ListViewControl1.ListViewItemSorter = New ListViewComparer(2, SortOrder.Ascending)
ListViewControl1.Sort()