[英]How to sort a DateTime-column in DataView?
I have a gridview with some columns and I need to sort the gridview by a date-column. 我有一些列的gridview,我需要按日期列对gridview进行排序。 But I fail in sorting it correctly. 但是我无法正确排序。 This is the code that I use: 这是我使用的代码:
dt.DefaultView.Sort = "Meldingsdatum asc";
gvOutlookMeldingen.DataSource = dt;
gvOutlookMeldingen.DataBind();
Can someone help me, please. 有人能帮助我吗。
DataView stores date or anything as string type. DataView将日期或任何内容存储为字符串类型。 Thus when you sort it sort by string. 因此,当您对它排序时,它按字符串排序。 To sort it as DateTime , you need to convert it to DateTime before adding any data as follows, 要将其排序为DateTime,您需要先将其转换为DateTime,然后再添加以下数据,
dt.Columns["Date"].DataType = Type.GetType("System.DateTime"); dt.Columns [“ Date”]。DataType = Type.GetType(“ System.DateTime”);
Is you column of type DateTime, if not then it probably needs to be. 您是DateTime类型的列,如果不是,则可能需要。 Do this right at the start before you populate the table. 在填充表格之前,请一开始就执行此操作。 Alternatively you could create a second column of type DateTime and use that but it's a little messy :-) 或者,您可以创建第二个类型为DateTime的列并使用它,但这有点混乱:-)
My code snippet hopefully shows the need to set the column as typeof(DateTime) before you can sort it properly 我的代码段希望显示在正确排序之前,需要将该列设置为typeof(DateTime)
EntityCollection result = serviceProxy.RetrieveMultiple(querybyattribute);
DataTable dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created On", typeof(DateTime));
foreach (Entity entity in result.Entities)
{
DataRow dr = dt.NewRow();
dr["Title"] = entity.Attributes["title"].ToString();
dr["Created On"] = entity.Attributes["createdon"];
dt.Rows.Add(dr);
}
DataView dv = dt.DefaultView;
dv.Sort = "Created On desc";
DataTable sortedDT = dv.ToTable();
dataGridView1.DataSource = sortedDT;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.