简体   繁体   English

C#按日期对Datagrid列进行排序

[英]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.日期的格式为 dd/mm/yy。

Example (sorted oldest first):示例(先排序最旧):

10/12/08 <--December 10/09/08 <--September 12/12/08 <--December 10/12/08 <--十二月 10/09/08 <--九月 12/12/08 <--十二月

Many thanks非常感谢

Is the source a datatable?源是数据表吗? If so, you'll probably need to specify that the column in question is of type DateTime:如果是这样,您可能需要指定相关列的类型为 DateTime:

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

Hope that helps!希望有帮助!

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.一种是格式化的 (varchar),另一种是日期时间数据类型。

Say the stored procedure returns the colums : COLUMN_STRING_FORMAT and COLUMN_DATETIME_FORMAT假设存储过程返回列:COLUMN_STRING_FORMAT 和 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"/> <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.它指的是 DateTime 数据类型中的列。

This worked for me when I was sorting on date in DD-MMM-YYYY format.当我以 DD-MMM-YYYY 格式对日期进行排序时,这对我有用。

Try this, it worked for me.试试这个,它对我有用。

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

Replace the colNum with the actual column number.用实际的列号替换colNum The d is for short date. d是短日期。 I also have military time in mine so I had to add HH:mm:ss for the time blocks.我也有军事时间,所以我不得不为时间块添加HH:mm:ss

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)或整个列的类似内容(请参阅列的 DefaultCellStyle)

When the datagrid is not bound to a datasource and the dataGrid is filled row by row, the following approach works for me:当 datagrid 未绑定到数据源并且 dataGrid 逐行填充时,以下方法对我有用:

//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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM