2

gridview 中的日期排序无法正常工作。

字段名:丢失日期数据类型:nvarchar(255)

在 sql 中,数据类型是 nvarchar 因为日期字段也有一些格式化的字符串值(例如:A90317,A00921 像这样)

从数据库中检索数据时,将数据转换为日期格式并将其绑定到网格中。

  SELECT name,location,convert(date,lossdate, 101) as LossDate from valuation

我的预期结果是这样的

NULL

NULL

NULL

A90118

A90317

A00921 

2004-05-27

2004-10-26

2010-07-14

2010-10-05

2011-04-07

null应该先来

格式化字符串日期格式排在第二位,

正确的日期格式接下来应该以排序方式出现

在gridview中,lossdate是这样的

<asp:BoundField DataField="LossDate" HeaderText="Loss Date" SortExpression="LossDate" 
   dataformatstring="{0:MM/dd/yyyy}"  />

请帮我解决这个问题

4

2 回答 2

1

Query如果你想避免编码,你可以试试下面Front-End

select name,location,Lossdate 
  from (select top (select COUNT(*) 
                      from valuation 
                     where ISDATE(Lossdate) = 0)  name,location,Lossdate  
          from valuation 
         Where ISDATE(Lossdate) = 0 
         order by Lossdate) T1
 union all
select name,location,Lossdate 
  from (select top (select COUNT(*) 
                      from valuation 
                     where ISDATE(Lossdate) <> 0) name,location,Lossdate  
          from valuation 
         Where ISDATE(Lossdate) <> 0 
         order by convert(date,Lossdate, 120)) T2
于 2013-07-10T07:27:20.550 回答
0
var temp = table.AsEnumerable()
 .OrderBy(x => x.Field<string>("LossDate") !=null)
    .ThenByDescending(p => !DateTime.TryParse(p.Field<string>("LossDate"), out dt))
    .ThenBy(x => x.Field<string>("LossDate"));
var result =temp.AsDataView().ToTable();

并在上面设置为 girdview 的 DataSource

样本 :

DataTable table = new DataTable();
table.Columns.Add("LossDate", typeof(string));
table.Rows.Add(new DateTime(2004, 05, 27));
table.Rows.Add(DBNull.Value);
table.Rows.Add("A90317");
table.Rows.Add(new DateTime(2009, 06, 27));
table.Rows.Add("A90118");
table.Rows.Add(DBNull.Value);
table.Rows.Add("A00921");
table.Rows.Add(DBNull.Value);
table.Rows.Add(new DateTime(2005, 06, 27));
DateTime dt;
var temp = table.AsEnumerable()
 .OrderBy(x => x.Field<string>("LossDate") !=null)
    .ThenByDescending(p => !DateTime.TryParse(p.Field<string>("LossDate"), out dt))
    .ThenBy(x => x.Field<string>("LossDate"));
var result =temp.AsDataView().ToTable();

结果 :

LossDate 
null  
null  
null  
A00921 
A90118 
A90317 
27/05/2004 12:00:00 AM 
27/06/2005 12:00:00 AM 
27/06/2009 12:00:00 AM 
于 2013-07-10T07:01:04.077 回答