El código que sigue es un ejemplo o una de las formas, siempre hay mas de una forma :), de como se puede lograr esta tarea.-
- SortingPaging.aspx (nuestra página aspx)
<asp:GridView ID="gridSample" runat="server" AutoGenerateColumns="false"- SortingPaging.aspx.cs (nuestro archivo de code behind)
AllowPaging = "true" OnPageIndexChanging = "gridView_PageIndexChanging"
PageSize = "5"
AllowSorting = "true" OnSorting = "gridView_Sorting">
<Columns>
<asp:BoundField HeaderText="Nombre"
DataField="Nombre"
SortExpression = "Nombre" />
<asp:BoundField HeaderText="Edad"
DataField="edad"
SortExpression = "edad" />
</Columns>
</asp:GridView>
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SortingPaging : Page {
protected void Page_Load(object sender, EventArgs e) {
DataSet ds = new DataSet();
// Aqui llenamos nuestro DataSet
DataView dv = ds.Tables[0].DefaultView;
dv = sortDataView(dv, true);
gridSample.DataSource = dv;
gridSample.DataBind();
}
private string GridSampleSortDirection {
get { return ViewState["SortDirection"] as string ?? "ASC"; }
set { ViewState["SortDirection"] = value; }
}
private string GridSampleSortExpression {
get { return ViewState["SortExpression"] as string ?? "Nombre"; }
set { ViewState["SortExpression"] = value; }
}
private string getSortDirection() {
switch (GridSampleSortDirection) {
case "ASC":
GridSampleSortDirection = "DESC";
break;
case "DESC":
GridSampleSortDirection = "ASC";
break;
}
return GridSampleSortDirection;
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e) {
gridSample.DataSource = sortDataView(gridSample.DataSource as DataView, true);
gridSample.PageIndex = e.NewPageIndex;
gridSample.DataBind();
}
protected DataView sortDataView(DataView dataView, bool isPageIndexChanging) {
if (isPageIndexChanging) {
dataView.Sort = string.Format("{0} {1}",
GridSampleSortExpression,
GridSampleSortDirection);
} else {
dataView.Sort = string.Format("{0} {1}",
GridSampleSortExpression,
getSortDirection());
}
return dataView;
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e) {
GridSampleSortExpression = e.SortExpression;
int pageIndex = gridSample.PageIndex;
gridSample.DataSource = sortDataView(gridSample.DataSource as DataView, false);
gridSample.DataBind();
gridSample.PageIndex = pageIndex;
}
}