Skip to main content

Sorting Dates in a DataGridView

  • February 15, 2013
  • 0 replies
  • 0 views

Problem:

If you store dates in a DataGridView TextBox column then it will sort the column in Alphabetical order. This makes the dates out of order when dd/mm/ccyy is the format.

How can you force the sort to sort based on date order ?

Resolution:

You can perform custom sorts by handling the Sort_Compare event.

An example that would sort in correct date order would be:-

       method-id.  "dataGridView1_SortCompare" final private.

       01 ls-date1         type "System.DateTime".

       01 ls-date2         type "System.DateTime".

       procedure division using by value sender as object e as type "System.Windows.Forms.DataGridViewSortCompareEventArgs".

       

      ***** Try Parsing as a Date. If its a date then sort as a date rather then the defaut method.     

           if type "System.DateTime"::"TryParse"(e::"CellValue1"::"ToString"(), ls-date1) and

              type "System.DateTime"::"TryParse"(e::"CellValue2"::"ToString"(), ls-date2)           

               set e::"SortResult" to type "System.DateTime"::"Compare"(ls-date1 , ls-date2)

               set e::"Handled" to true

           else

               set e::"Handled" to false

           end-if

       

       end method "dataGridView1_SortCompare".

Attached to this an a complete working example (Built in Net Express V5.1).

Old KB# 4442