简体   繁体   English

如何对GridView排序?

[英]How do I sort a GridView?

ASP.NET GridView sorting: I want to change the sorting direction from ascending to descending when I click the column name. ASP.NET GridView排序:我想在单击列名时将排序方向从升序更改为降序。 But by default, sorting direction always showing ascending. 但默认情况下,排序方向始终显示为升序。 Am I missing any property setting to toggle sorting direction? 我是否缺少任何可切换排序方向的属性设置? Any help greatly appreciated. 任何帮助,不胜感激。 Thanks. 谢谢。

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{

    DataTable dataTable = myDataTable(strSQL);

    if (dataTable != null)
    {

        DataView dataView = new DataView(dataTable);

        dataView.Sort = e.SortExpression + " " + SortDirection(e.SortDirection);

        gridView.DataSource = dataView;

        gridView.DataBind();

     }

}
//e.SortDirection always showing ascending

aspx gridview column design for sorting: 用于排序的aspx gridview列设计:

<asp:BoundField DataField="CREATE_DATE" HeaderText="Create Date" SortExpression="CREATE_DATE" />

Did you try setting the AllowSorting attribute of the GridView to true in the markup? 您是否尝试过在标记中将GridViewAllowSorting属性设置为true?

<asp:GridView ID="GridView1" runat="server" AllowSorting="True">
    <Columns>
        ...
    </Columns>
</asp:GridView>

Or, you could do it in your code behind after the DataBind: 或者,您可以在DataBind之后的代码中执行此操作:

GridView1.AllowSorting = true;

This attribute allows the user to click on the column headers to sort on that column. 此属性允许用户单击列标题以对该列进行排序。

Edit: You actually have to create logic to decide whether to sort ascending or descending ( e.SortDirection will only help you if your using a "data source control" like SQLDataSource ). 编辑: 实际上,你必须创建逻辑来决定是否排序升序或降序e.SortDirection如果您使用“数据源控件”像只会帮助你SQLDataSource )。 Then you can just change your dataView.Sort code to some like this: 然后,您可以将dataView.Sort代码更改为如下所示:

if(someCondition)
    dataView.Sort = e.SortExpression + " DESC";
else
    dataView.Sort = e.SortExpression + " ASC";

Where someCondition is your logic for deciding which way to sort (for instance you could keep track of what the last sort direction was for that column, then do the opposite if the user clicks it again). 其中, someCondition是决定排序方式的逻辑(例如,您可以跟踪该列的最后排序方向,如果用户再次单击,则执行相反的操作)。

Before you bind the data, sort it in the direction you want and then do: 绑定数据之前,请按所需方向对其进行排序,然后执行以下操作:

gridview.DataSource=data;
gridview.DataBind();

If your datasource is SQLDataSource or something similar, just make sure your select statement does the sorting the way you want initially. 如果您的数据源是SQLDataSource或类似的东西,只需确保您的select语句按照您最初想要的方式进行排序。

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

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