Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 13:09pm

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.
 
Share this answer
 
Comments
Maciej Los 15-Feb-20 15:25pm    
5ed!
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.
 
Share this answer
 
Comments
phil.o 14-Feb-20 10:01am    
Sensible advice :)
Maciej Los 15-Feb-20 15:24pm    
Thank you, Olivier.
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.
 
Share this answer
 
Instead of String Column, you can use DateTime Column and set it's DefaultCellStyle.Format property to any datetime format.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900