1

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>
1
  • You are correct that the query needs to handle the sort direction. You also need to decide where to store current sort direction either in view state, url, or session. Commented Sep 21, 2012 at 21:50

2 Answers 2

2

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, At the end of your code you say "//load the data with this SortExpression and DataBind the Grid". do you mean "//load the data with this SortExpression and currentSortColumn and DataBind the Grid"
@user1438082: No, as you can see the SortExpression contains both, the currentSortColumn + SortDirection. That means you only have to append the SortExpression to the end of your sql's ORDER BY. This approach supports sorting in both directions, if the user clicks consecutively on the same column the SortDirection changes for that column. Note that the property SorteExpression has a default sort, change it accordingly.
1

i have a method more simple in few lines: (code in vb.net, for translation in c# it is easy)

Dim SortDirection As String, SortExpression As String
SortExpression = e.SortExpression
If (SortExpression = ViewState("SortExpression") And ViewState("SortDirection") = "asc") Then
    SortDirection = "desc"
Else
    SortDirection = "asc"
End If
ViewState("SortDirection") = SortDirection
ViewState("SortExpression") = SortExpression

Dim dt As Data.DataTable = ds.Tables(0) '<<<< fill ds with a method
dt.DefaultView.Sort = SortExpression & " " & SortDirection

GridView1.DataSource = dt.DefaultView
GridView1.DataBind()

that's all. it's easy then to place this code in a generic class, to apply to other gridviews

1 Comment

What i found is its easier by far to use telerik or devexpress gridview controls. They have functionality built in that will save you weeks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.