分类
笔记

VB.Net实现点击ListView Column排序

ListView是VB.Net很重要的一个控件。但是如何针对某一个Column排序,如何实现点击Column排序,CLR并没有提供相关方法。

本文转载自”新兴网络“,为适应读者需求,对转载文章做出了部分修改。你可以:访问原文章

今天,我们来实现这个功能。

首先,我们给项目里新建一个类,名字取如:“ColumnSort.vb”即可,然后添加如下代码:

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

然后在ListView的ColumnClick事件中添加如下代码:

'将ListView1改为自己的ListView的名字
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

发表评论

电子邮件地址不会被公开。 必填项已用*标注