简体   繁体   中英

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. 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:

<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?

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

Or, you could do it in your code behind after the 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 ). Then you can just change your dataView.Sort code to some like this:

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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