'フォームのカラムクリックイベント
Private Sub ListView1_ColumnClick(ByVal sender As Object, _
ByVal e As System.Windows.Forms.ColumnClickEventArgs) _
Handles ListView1.ColumnClick
Static no(5) As Integer '列のソート状態保持用
If no(e.Column) = 0 Then
'初回または昇順
Me.ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, 0)
no(e.Column) = 1 '次回は降順
Else
'降順
Me.ListView1.ListViewItemSorter = New ListViewItemComparer(e.Column, 1)
no(e.Column) = 0 '次回は昇順
End If
End Sub
'ListViewItemComparerクラスをフォームコードに追加
Class ListViewItemComparer
Implements IComparer
Private col As Integer
Private sort As Integer
Public Sub New()
col = 0
sort = 0
End Sub
Public Sub New(ByVal column As Integer, ByVal sortflg As Integer)
'column : 列番号
'sortflg : ソート(0=昇順,1=降順)
'--------------------------------
col = column
sort = sortflg
End Sub
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements IComparer.Compare
If sort = 0 Then
'昇順
Return [String].Compare(CType(x, ListViewItem).SubItems(col).Text, _
CType(y, ListViewItem).SubItems(col).Text)
Else
'降順
Return -[String].Compare(CType(x, ListViewItem).SubItems(col).Text, _
CType(y, ListViewItem).SubItems(col).Text)
End If
End Function
End Class
降順にするには マイナスを付けるだけだったとは知らなかった。