2012-12-11 57 views
2

我使用ASP.NET和C#。这是我的代码。如何在gridview中对日期列进行排序?

private const string ASCENDING = "ASC"; 
    private const string DESCENDING = "DESC"; 
    public SortDirection GridViewSortDirection 
    {  
     get  
     {   
      if (ViewState["sortDirection"] == null)    
       ViewState["sortDirection"] = SortDirection.Ascending;   
      return (SortDirection) ViewState["sortDirection"];      
     }  
     set { ViewState["sortDirection"] = value; } 
    } 

    public string SortExpression 
    { 
     get 
     { 
      if (ViewState["sortExpression"] == null) 
       ViewState["sortExpression"] = "JobNumber"; 
      return ViewState["sortExpression"] as string; 
     } 
     set { ViewState["sortExpression"] = value; } 
    } 
    protected void OnSorting(object sender, GridViewSortEventArgs e) 
    { 
      SortExpression = e.SortExpression; 
      if (GridViewSortDirection == SortDirection.Ascending) 
      { 
       GridViewSortDirection = SortDirection.Descending; 
      } 
      else 
      { 
       GridViewSortDirection = SortDirection.Ascending; 
      } 
      BindGrid(); 
    } 

我正在对所有列进行排序并正常工作。但是与日期栏一样,按照这个顺序(dd/mm/yyyy)。

  • 30/11/2012
  • 2012年10月12日
  • 2012年9月10日

    <asp:BoundField DataField="ReportedDate" HeaderText="Reported Date" SortExpression="ReportedDate" DataFormatString="{0:DD/MM/YYYY}" HtmlEncode="false" /> 
    

此列的数据类型是日期。

如何做到这一点?我做错了吗?

+0

在您的代码“30/11/2012”中,其他日期被视为字符串,只有字符串排序正在发生。 – sajanyamaha

+0

谢谢..我知道,但我不知道为什么字符串排序正在发生。我宣布这只作为日期类型..你可以给我任何提示? – Giri

回答

6

有两个选项

1.To排序在SQL级别,这是最好的和适当的方法,结合所产生的结果集在gridview中。

2.要将DataTable与查询输出绑定并在数据表上运行排序,然后将其绑定到gridview。 请记住将数据类型添加到数据表列accTable.Columns.Add("Date",typeof(DateTime));

+0

是啊..我通过第一种方法绑定,如直接绑定结果集grid.any有关为什么字符串排序正在发生的想法? – Giri

+0

第一种方法意思就像'select * from recentLogin order by the_date',之后你只需要绑定它,为什么你要重新排序呢? – sajanyamaha

+0

谢谢..我的东西很复杂..现在它工作.. – Giri

1

数据库中该列的数据类型是什么?它看起来像是一个字符串字段而不是一个DateTime字段。如果是这种情况,您需要先修复数据类型,然后才能在gridview上不更改任何内容的情况下获得正确的排序顺序。

试图改变

<asp:BoundField DataField="ReportedDate" HeaderText="Reported Date" SortExpression="ReportedDate" DataFormatString="{0:DD/MM/YYYY}" HtmlEncode="false" /> 

<asp:TemplateField SortExpression="ReportedDate"> 
    <ItemTemplate> 
      <asp:label id="lblDate" runat="server" text='<%# Eval("ReportedDate", "{0:DD/MM/YYYY}") %>' /> 
    </ItemTemplate></asp:TemplateField> 
+0

就像我在帖子中指定的那样,它是日期的类型。 – Giri

+0

您是否尝试将BoundField更改为TemplateField? – GeorgesD

+0

谢谢..但它没有像以前一样工作。是我的代码隐藏是好的? – Giri

相关问题