Asp.net gridview sorting custom datasource

asp.netgridview

i have a gridview that is being populated ok. Now i want to enable sorting. Ive done all the required code – namely enabling sorting on the markup and providing the event to call when a user sorts.

its the sort event that im lost with – i have tried a few implementations from Google but im not too sure. Essentially am i corect in saying that i need to provide new queries back to the server depending on what column the user wants to sort by and ASC or DESC also? if so it sounds like alot of more work….more queries.

thanks
damo

Code Behind to Bind the grid

 // Load the main homepage data to the grid
                    FAServices fServices = new FAServices(sConn);
                    FAAuditOverallStatusLatest fAuditOverallStatusLatest = new FAAuditOverallStatusLatest(sConn);
                    GridViewMain.DataSource = fAuditOverallStatusLatest.getAuditOverallStatusLatest();
                    GridViewMain.DataBind();

Code behind to sort

protected void GridViewMain_Sorting(object sender, GridViewSortEventArgs e)
{

    // Switch statements required here along with Query for each column i have in the grid




}

Grid Markup

<asp:GridView ID="GridViewMain" OnRowDataBound="GridViewMainRowDataBound" OnPageIndexChanging="GridViewMain_PageIndexChanging"
                                        runat="server"  AllowPaging="True" PageSize="50" PagerSettings-Position="TopAndBottom"
                                        CssClass="mGrid"
                                        PagerStyle-CssClass="pgr"
                                        AlternatingRowStyle-CssClass="alt data-row"
                                        OnRowCreated="GridViewMain_RowCreated"                          
                                        RowStyle-CssClass="data-row"                                        
                                        AllowSorting="True"
                                        OnSorting="GridViewMain_Sorting"
                                        >
                                     </asp:GridView>

Best Answer

Am i corect in saying that i need to provide new queries back to the server depending on what column the user wants to sort by and ASC or DESC also? If so it sounds like alot of more work....more queries.

Yes, you're correct. You need to query your datasource again to apply the new sort. But the last sentence is not correct. You just need to change the ORDER BY of your sql (or whatever you use to order the DataSource). You can use one ViewState variable for both, the order-column and the direction(you need to persist it across postbacks, therefore the ViewState). I'll show you an example:

First, you need to set the SortExpression.

<asp:TemplateField HeaderText="Name" SortExpression="Name">
    <ItemTemplate>
        <a href='sometest.aspx?ID=<%# DataBinder.Eval(Container.DataItem, "TestID").ToString()%>'><%# DataBinder.Eval(Container.DataItem, "Type").ToString()%></a>
    </ItemTemplate> 
</asp:TemplateField>    
<asp:TemplateField HeaderText="Address" SortExpression="Address">
    <ItemTemplate>
                <div align="right"><%# (DataBinder.Eval(Container.DataItem, "HouseNumber"))%></div>
    </ItemTemplate> 
</asp:TemplateField>            

in the codebehind you can store the current SortExpression and the SortDirection in ViewState:

private string SortExpression {
    get {
        if(String.IsNullOrWhiteSpace((String)ViewState["SortExpression"])
            ViewState["SortExpression"] = "Name ASC";

        return (String)ViewState["SortExpression"];
    }
    set { ViewState["SortExpression"] = value; }
}

Here's the Sorting event handler. Note that BindGrid is the method where you set the DataSource and call GridView.DataBind

protected void theGrid_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
{
    string currentSortColumn = null;
    string currentSortDirection = null;
    currentSortColumn = this.SortExpression.Split(' ')[0];
    currentSortDirection = this.SortExpression.Split(' ')[1];

    if (e.SortExpression.Equals(currentSortColumn)) {
        //switch sort direction
        switch (currentSortDirection.ToUpper()) {
            case "ASC":
                this.SortExpression = currentSortColumn + " DESC";
                break;
            case "DESC":
                this.SortExpression = currentSortColumn + " ASC";
                break;
        }
    } else {
        this.SortExpression = e.SortExpression + " ASC";
    }

    //load the data with this SortExpression and DataBind the Grid
    BindGrid();
}
Related Topic