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
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 theDataSource
). You can use oneViewState
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.
in the codebehind you can store the current
SortExpression
and theSortDirection
inViewState
:Here's the
Sorting
event handler. Note thatBindGrid
is the method where you set theDataSource
and callGridView.DataBind