Results 1 to 3 of 3

Thread: Sorting DataGridView depending on String or Numeric content

Threaded View

  1. #3

    Thread Starter
    Lively Member
    Join Date
    May 2011
    Posts
    87

    Re: Sorting DataGridView depending on String or Numeric content

    Well, I have just found a very simple way of doing this for which I claim no credit!

    But first, it seems that the default mode for a DataGridView cell is "TextBox" (as you will notice if you add a column) and surprisingly if you do the following (as I have done), it allows it

    Code:
    Grid1.Item(5, intRow).Value = 17.356
    Even if you have Option Strict on (which you should IMHO) but it stores it as a String (news to me but I should have realised)

    Anyway, if you add the following routine, it should work like magic

    Code:
    Private Sub Grid_SortCompare(sender As Object, e As DataGridViewSortCompareEventArgs) Handles _
      Grid1.SortCompare,
      Grid2.SortCompare,
      Grid3.SortCompare,
      Grid4.SortCompare
    
      Dim MyGrid As DataGridView
    
      MyGrid = DirectCast(sender, DataGridView)
    
      If GridColumnNumericLGH(MyGrid, e.Column.Index) = False Then
          Return
        Else
          e.SortResult = If(Cint(e.CellValue1) < CInt(e.CellValue2), -1, 1)
          e.Handled = True
      End If
    
    End Sub
    
    Public Function GridColumnNumericLGH(MyGrid As DataGridView, intColumn As Integer) As Boolean
      ' Written 7th November 2014
    
      Dim intRow As Integer
    
      GridColumnNumericLGH = True
      For intRow = 0 to MyGrid.RowCount - 1
        If IsNumeric(MyGrid.Item(intColumn, intRow).Value) = False Then
          GridColumnNumericLGH = False
          Exit Function
        End If
      Next
    
    End Function
    I hope this heps somebody
    Last edited by wavering; Nov 7th, 2014 at 07:31 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width