Thursday, May 1, 2008

Update - Datagridview - Sorting Numeric Columns that are not bound...

I found an example on a website that did what I mention above but does it a lot better.  Below is the pasted code

    Private Sub grd_SortCompare(ByVal sender As
Object, ByVal e As System.Windows.Forms.DataGridViewSortCompareEventArgs) Handles grdList.SortCompare
        e.SortResult = CompareEx(e.CellValue1.ToString, e.CellValue2.ToString)
        e.Handled = True
        Exit Sub
    End Sub


    Public Function CompareEx(ByVal s1 As Object, ByVal s2 As Object) As Integer

        Try
' convert the objects to string if possible.
            Dim a As String = CType(s1, String)
            Dim b As String = CType(s2, String)

' If the values are the same, then return 0 to indicate as much
            If s1 = s2 then return 0

' Look to see if either of the values are numbers
            Dim IsNum1 As Boolean = IsNumeric(a)
            Dim IsNum2 As Boolean = IsNumeric(b)

' If both values are numeric, then do a numeric compare
            If IsNum1 And IsNum2 Then
                If Double.Parse(s1) > Double.Parse(s2) Then
                    Return 1
                ElseIf Double.Parse(s1) < Double.Parse(s2) Then
                    Return -1
                Else
                    Return 0
                End If
' If the first value is a number, but the second is not, then assume the number is "higher in the list"
            ElseIf IsNum1 And IsNum2 = False Then
                Return -1
' if the first values is not a number, but the second is, then assume the number is higher
            ElseIf IsNum1 = False And IsNum2 Then
                Return 1
            Else
' If both values are non nuermic, then do a normal string compare
                Return String.Compare(s1, s2)
            End If
        Catch ex As Exception
            Console.WriteLine(ex.ToString)
        End Try

' If we got here, then we failed to compare, so return 0
        return 0
    End Function

No comments: