I want to order a column in my grid view as a datetime but i feel it’s ordered as a string instead :
My code :
if (SortExpression.ToString() == "TransDate")
{
if (SortDirection == SortDirection.Ascending)
{
gv_Details1.DataSource = TransactionList.OrderBy(t => DateTime.Parse(t.TransDate)).ToList<UserTransactionDTO>();
}
else
{
gv_Details1.DataSource = TransactionList.OrderByDescending(t => DateTime.Parse(t.TransDate)).ToList<UserTransactionDTO>();
}
}
My aspx :
<asp:BoundField DataField="TransDate" HeaderText="Date" SortExpression="TransDate">
Part of the result ::
23/12/2012 09:51
27/9/2012 11:36
3/10/2012 12:28
2/10/2012 10:51
I think the problem is your using
DateTime.Parsein the linq sorting and your string has cases where the first and second parts could be the day or the month… remember the parsing is happening item by item so just because the first one parse one way doesn’t mean the second one will parse the same way.Your region default is probably month first which doesn’t work for the first couple so it knows that the first part is day so it uses that format. For the last couple dates, the first part does work for month so it parses month first as per the default. Or vice versa 🙂
Try using
DateTime.ParseExactlike this:Hopefully I picked the right format but if not just tweak it.