title: Sorting a DataGridView by date column using a custom IComparer
body: <p>I have a data grid view on a form with a date column and I would like to sort the column when a sort button is pressed.</p>
  
  <p>Here is the code for the button click event:</p>
  
  <pre><code>Private Sub DateOfBirthSortButton_Click(sender As Object, e As EventArgs) Handles DateOfBirthSortButton.Click
      PatientDataGridView.Sort(New DatabaseModule.DateComparer)
  End Sub
  </code></pre>
  
  <p>And for the comparer:</p>
  
  <pre><code>Public outputFile As String = "C:\Users\Patrick\Desktop\outputTest.txt"
  
  Public Class DateComparer
      Implements IComparer
  
      ' Compare the two dates
      Public Function Compare(ByVal rowX As Object, ByVal rowY As Object) As Integer Implements System.Collections.IComparer.Compare
  
          'Get the date value from the collection of cells in the row
          Dim dateX As String = rowX.Cells.Item(2).Value.ToString
          Dim dateY As String = rowX.Cells.Item(2).Value.ToString
  
          'Convert to a date
          Dim x As Date = DateTime.ParseExact(dateX, "dd-MM-yyyy", Nothing)
          Dim y As Date = DateTime.ParseExact(dateX, "dd-MM-yyyy", Nothing)
  
          'Compare
          Dim cmpDate As Integer = Date.Compare(x, y)
  
          Dim objWriter As New System.IO.StreamWriter(outputFile, True)
  
          objWriter.WriteLine(dateX &amp; " " &amp; dateY &amp; " " &amp; cmpDate)
          objWriter.Close()
  
          Return cmpDate
  
      End Function
  End Class
  </code></pre>
  
  <p>I have added code which puts the results from the comparer into a text file so that I could see the results of each comparison.</p>
  
  <p>However, when the button is pressed, the comparer only compares the same row against itself, in a seemingly random order, sometimes multiple times.</p>
  
  <p>Here is the initial order (I've given the people numbers to show which order they should sort into):</p>
  
  <p><a href="https://i.stack.imgur.com/gSeob.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gSeob.png" alt="Initial ordering"></a></p>
  
  <p>And the resultant order after the sort button is pressed:</p>
  
  <p><a href="https://i.stack.imgur.com/xklrH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xklrH.png" alt="Resultant ordering"></a></p>
  
  <p>And the comparisons recorded in the text file:</p>
  
  <p><a href="https://i.stack.imgur.com/lmOgn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lmOgn.png" alt="Text file results"></a></p>
  
  <p>If anyone could explain to me how I can fix my problem I would be very grateful, thanks :)</p>