gridview中的日期排序无法正常工作。
字段名称:Lossdate 数据类型:nvarchar(255)
在sql中,数据类型为nvarchar,因为date字段也有一些格式化的字符串值 (例如:A90317,A00921这样)
从db中检索数据时,我将数据转换为日期格式并将其绑定到网格中。
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中,损失日期就像这样
<asp:BoundField DataField="LossDate" HeaderText="Loss Date" SortExpression="LossDate"
dataformatstring="{0:MM/dd/yyyy}" />
请帮我解决这个问题
答案 0 :(得分: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
答案 1 :(得分: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的数据源
示例:
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