VB.NET : Sorting Dates in DataGridView

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stevelaw
    New Member
    • Nov 2007
    • 2

    VB.NET : Sorting Dates in DataGridView

    Hi,

    I'm using VB 2005 and I have a DataGridView that I am populating manually.

    e.g.
    [code=vbnet]
    Private Sub List_Dates()

    dgvDates.Rows.C lear()

    Dim c As Integer
    Dim Row() As String = New String(3) {}

    For c = 0 To WorkstationCoun t
    Row(0) = Workstations(c)
    Row(1) = FormatDateTime( DatesAssign(c), DateFormat.Shor tDate)
    Row(2) = FormatDateTime( DatesAgent(c), DateFormat.Shor tDate)
    dgvDates.Rows.A dd(Row)
    Next

    End Sub[/code]

    The context is that I'm reading in a set of files (one for each workstation) with various data in that I am parsing, including two dates, then saving this data in various arrays before putting in DataGridViews to display.

    Anyway, everything works fine except that when I click on the column header to sort the two dates columns, they sort as a string, not as a date.

    I've seen various very similar questions, but none of them answer the question for me (I suppose primarily because I am not binding a data source).

    What can I do to get these columns to sort as a date?

    Thanks,

    Steve
    Last edited by Frinavale; Nov 21 '07, 09:33 PM. Reason: Added [code] tags
  • stevelaw
    New Member
    • Nov 2007
    • 2

    #2
    Okay, never mind. Pretty simple solution in the end.
    [code=vbnet]
    Private Sub dgvDates_SortCo mpare(ByVal sender As Object, ByVal e As DataGridViewSor tCompareEventAr gs) Handles dgvDates.SortCo mpare

    If e.Column.Index = 0 Then
    e.SortResult = System.String.C ompare(e.CellVa lue1, e.CellValue2)
    Else
    e.SortResult = System.DateTime .Compare(e.Cell Value1, e.CellValue2)
    End If

    e.Handled = True

    End Sub[/code]

    Comment

    • skalluparambil
      New Member
      • Nov 2007
      • 1

      #3
      Stevelaw,

      You are simply great. I Have been hunting this ans since 4 days. I was going to implement icomparable and all those stuff.
      You have made it so simple.

      i registered with the scripts just to leave a thankyou note to you.

      Happy thanksgiving. You made my day!

      Originally posted by stevelaw
      Okay, never mind. Pretty simple solution in the end.

      Private Sub dgvDates_SortCo mpare(ByVal sender As Object, ByVal e As DataGridViewSor tCompareEventAr gs) Handles dgvDates.SortCo mpare

      If e.Column.Index = 0 Then
      e.SortResult = System.String.C ompare(e.CellVa lue1, e.CellValue2)
      Else
      e.SortResult = System.DateTime .Compare(e.Cell Value1, e.CellValue2)
      End If

      e.Handled = True

      End Sub

      Comment

      Working...