1 Previous Next 

DataGridView: Custom Sort


Someone asked me about doing a custom sort on a datagridview during my datagridview session at code camp. Unfortunately this will not work if the datagridview is bound to a datasource. This example adds numbers as string data to a datagridview. When you sort this column the values will not be in numeric order. This example converts the string to a number and sorts based on the number.
Untitled 9
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, _
               ByVal e As System.EventArgsHandles MyBase.Load
        DataGridView1.ColumnCount = 1
        DataGridView1.Columns(0).HeaderText = "String"
        For x As Integer = 0 To 100
            DataGridView1.Rows.Add(New String() {x.ToString})
        Next
    End Sub
    Private Sub DataGridView1_SortCompare(ByVal sender As Object, _
                ByVal e As System.Windows.Forms.DataGridViewSortCompareEventArgs) _
                 Handles DataGridView1.SortCompare
        Dim intValue1, intValue2 As Integer
        If Not Integer.TryParse(e.CellValue1.ToString, intValue1) Then Return
        If Not Integer.TryParse(e.CellValue2.ToString, intValue2) Then Return
        If intValue1 = intValue2 Then
            e.SortResult = 0
        ElseIf intValue2 > intValue1 Then
            e.SortResult = -1
        Else
            e.SortResult = 1
        End If
        e.Handled = True
    End Sub
End Class



1 Previous Next