Click here to Skip to main content
14,454,945 members
Rate this:
Please Sign up or sign in to vote.
See more:
i have a datagridview column which is type of string and the string values are time(ex: 12:15:00 AM), i want to sort the column in order as follows

12:15:00 AM
12:20:00 AM
1:50:00 AM
4:00:00 AM
11:00:00 AM
2:00:00 PM
5:00:00 PM

so on.

However the result are different and its sorting based on numbers.
is there anything i can do to achieve it, please help.

What I have tried:

<pre>usrgrid1.Sort(usrgrid1.Columns["TimeUpdated"], ListSortDirection.Ascending);
Posted
Updated 15-Feb-20 14:09pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

You could try to use the other overload of the Sort method:
DataGridView.Sort Method (System.Windows.Forms) | Microsoft Docs[^]
and create an IComparer which would transform column values back to DateTime values before comparisons. You can base your implementation on provided example.
   
Comments
Maciej Los 15-Feb-20 15:25pm
   
5ed!
Rate this:
Please Sign up or sign in to vote.

Solution 2

Quote:
is there anything i can do to achieve it


Yes, you need to use proper data type: DateTime, instead of string! Then you'll be able to sort data correctly.
   
Comments
phil.o 14-Feb-20 10:01am
   
Sensible advice :)
Maciej Los 15-Feb-20 15:24pm
   
Thank you, Olivier.
Rate this:
Please Sign up or sign in to vote.

Solution 3

Quote:
is there anything i can do to achieve it, please help.

Only a few options:
- switch to 24 hours format (military time in USA). Sort can be done directly with a string in that format.
- use a datetime datatype, it is sortable.
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

Instead of String Column, you can use DateTime Column and set it's DefaultCellStyle.Format property to any datetime format.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100