Ben H
Ben H

Reputation:

C# Sorting Datagrid column by date

I have a column that contains dates, when I click the column header the column is sorted numerically and not by date. How would I sort this by date? The date is in the format dd/mm/yy.

Example (sorted oldest first):

10/12/08 <--December 10/09/08 <--September 12/12/08 <--December

Many thanks

Upvotes: 4

Views: 17994

Answers (5)

peregrinus
peregrinus

Reputation: 167

When the datagrid is not bound to a datasource and the dataGrid is filled row by row, the following approach works for me:

//Init 
dataGridView_records.Columns[0].DefaultCellStyle.Format = "dd/MM/yy HH:mm:ss";

then fill the datagrid as follows:

DateTime date = DateTime.ParseExact((String)drs["data"], "dd/MM/yy HH:mm:ss", CultureInfo.InvariantCulture);
object[] gdr = new object[1] { date };//add the other columns data here
dataGridView_records.Rows.Add(gdr); 

Upvotes: 0

Endkill
Endkill

Reputation: 11

Try this, it worked for me.

dataGridView1.Columns[colNum].DefaultCellStyle.Format = "d";

Replace the colNum with the actual column number. The d is for short date. I also have military time in mine so I had to add HH:mm:ss for the time blocks.

Upvotes: 1

stepd
stepd

Reputation: 11

You should use cell format

dgv.Rows[rowId].Cells["colCreated"].Style.Format = "HH:mm :: dd/MM/yyyy";

or something like this for the whole column (see DefaultCellStyle for column)

Upvotes: 1

Jaye
Jaye

Reputation: 21

If the data source is from a stored procedure, return the date as two columns in the dataset. One is formatted (varchar) and another is in the Date time data type.

Say the stored procedure returns the colums : COLUMN_STRING_FORMAT and COLUMN_DATETIME_FORMAT

In the markup for grid,

<asp:BoundColumn DataField="COLUMN_STRING_FORMAT" SortExpression="COLUMN_DATETIME_FORMAT" DataFormatString="{0:dd-MMM-yyyy}" /> <asp:BoundColumn DataField="COLUMN_DATETIME_FORMAT" Visible="false"/>

Note the Sort Expression in the first line. It refers to the column in DateTime data type.

This worked for me when I was sorting on date in DD-MMM-YYYY format.

Upvotes: 2

Gunny
Gunny

Reputation: 1166

Is the source a datatable? If so, you'll probably need to specify that the column in question is of type DateTime:

myDataTable.Columns["ColumnName"].DataType = System.Type.GetType("System.Date");

Hope that helps!

Upvotes: 10

Related Questions