C# Sorting Datagrid column by date

16,745

Solution 1

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!

Solution 2

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.

Solution 3

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.

Solution 4

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)

Share:
16,745

Related videos on Youtube

Admin
Author by

Admin

Updated on April 18, 2022

Comments

  • Admin
    Admin about 2 years

    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