重写DataGridView的sort方法 自定义排序

Sort(DataGridViewColumn,ListSortDirection)重载
注意:当通过设置 DataSource 属性将 DataGridView 控件绑定到外部数据源时,Sort(DataGridViewColumn,ListSortDirection) 方法重载不能用于未绑定列。此外,当 VirtualMode 属性为 true 时,可以仅为绑定列调用此重载。若要确定某一列是否为数据绑定列,请检查 IsDataBound 属性值。

Sort(IComparer)重载
注意:仅当 DataGridView 控件未绑定到外部数据源且 VirtualMode 属性值为 false 时,Sort(IComparer) 方法重载才起作用。若要为绑定到外部数据源的列自定义排序,必须使用由该数据源提供的排序操作。在虚拟模式中,必须为未绑定列提供您自己的排序操作。
Sort(IComparer) 方法重载不设置 SortedColumn 和 SortOrder 属性,因此必须总是设置 DataGridViewColumnHeaderCell.SortGlyphDirection 属性以显示排序标志符号。
Public Class RowComparer
 Implements System.Collections.IComparer

 Private sortOrderModifier As Integer = 1

 Public Sub New(ByVal sortOrder As SortOrder)
  If sortOrder = sortOrder.Descending Then
   sortOrderModifier = -1
  ElseIf sortOrder = sortOrder.Ascending Then
   sortOrderModifier = 1
  End If
 End Sub

 Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
  Dim DataGridViewRow1 As DataGridViewRow = CType(x, DataGridViewRow)
  Dim DataGridViewRow2 As DataGridViewRow = CType(y, DataGridViewRow)

  ' Try to sort based on the Last Name column.
  Dim CompareResult As Integer = System.String.Compare( _
  DataGridViewRow1.Cells(1).Value.ToString(), _
  DataGridViewRow2.Cells(1).Value.ToString())

  ' If the Last Names are equal, sort based on the First Name.
  If CompareResult = 0 Then
   CompareResult = System.String.Compare( _
   DataGridViewRow1.Cells(0).Value.ToString(), _
   DataGridViewRow2.Cells(0).Value.ToString())
  End If

  Return CompareResult * sortOrderModifier
 End Function
End Class
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
 If RadioButton1.Checked = True Then
  DataGridView1.Sort(New RowComparer(SortOrder.Ascending))
 ElseIf RadioButton2.Checked = True Then
  DataGridView1.Sort(New RowComparer(SortOrder.Descending))
 End If
End Sub

SortCompare事件
注意:当 DataSource 属性已设置时,或者当 VirtualMode 属性值为 true 时,不会发生 SortCompare 事件。
Private Sub dgv_ResultList_SortCompare(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewSortCompareEventArgs) Handles dgv_ResultList.SortCompare
 Dim val1 As String = getDBStr(e.CellValue1).ToString.Replace(",", "")
 Dim val2 As String = getDBStr(e.CellValue2).ToString.Replace(",", "")
 If IsNumeric(val1) AndAlso IsNumeric(val1) Then
  If CDec(val1) = CDec(val2) Then
   e.SortResult = 0
  ElseIf CDec(val1) < CDec(val2) Then
   e.SortResult = -1
  ElseIf CDec(val1) > CDec(val2) Then
   e.SortResult = 1
  End If
 Else
  e.SortResult = String.Compare(val1, val2)
 End If
 e.Handled = True
End Sub

DataView.Sort属性

原文地址:https://www.cnblogs.com/justinsun/p/2211174.html