Yustme
Yustme

Reputation: 6265

sort on date column gridview

I got a gridview which auto generates columns. One of the columns is a date field. Somehow, i cant sort the date field. It's being interpreted as a string.

The data comes out a database. The datatype there is set on datetime.

This is the code in the aspx file:

<asp:BoundField DataField="date" HeaderText="date" SortExpression="date" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>

What am i doing wrong here?

Upvotes: 1

Views: 11459

Answers (2)

TonyL
TonyL

Reputation: 66

I realise this is a relatively old post but looking for a solution myself I figured this out.

If the Date is being populated as a string then you need to make sure it's not. To do this create the data for the table as a DataTable and when adding in the data use:

dt.Columns.Add("DateTime", System.Type.GetType("System.DateTime"));

This sorts the Date column out just as you would like it.

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460288

When you Format a value (no matter what data type it is), the result is a String. Any operations on the result (such as sorting) work with a String.

You should directly sort the Datasource of the Gridview on Database side.

Upvotes: 0

Related Questions