Girdview set in the ui page as below:
<asp:GridView ID="GridView_Data" AllowPaging="True" AllowSorting="True"
PageSize="5" runat="server" OnPageIndexChanging="GridView_Data_PageIndexChanging"
OnRowCreated="GridView_Data_RowCreated" OnSorting="GridView_Data_Sorting">
</asp:GridView>
below is the GridView_Data_PageIndexChanging
protected void GridView_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Button1_Click(sender,e);//used to select data from database
GridView_Data.PageIndex = e.NewPageIndex;
GridView_Data.DataBind();
}
the function below is used to select data from the database
protected void Button1_Click(object sender, EventArgs e)
{
//Response.Write("<script language='javascript'>alert('ok')</script>");
// Logger.Info("test log");
//log.Debug("Application loaded successfully.");
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
string connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["TestConnectionString"].ToString();
SqlConnection sc = new SqlConnection(connString);
SqlDataAdapter sa = new SqlDataAdapter("select * from dbo.DatabaseLog", sc);
ds = new DataSet();
sa.Fill(ds);
this.GridView_Data.DataSource = ds;
GridView_Data.DataBind();
}
Below are the functions regarding to sorting
protected string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
protected void Sorting(GridView gv, string sortExpression, SortDirection sortDirection)
{
// DataTable dataTable = gv.DataSource as Table;
DataTable dataTable = (DataTable)ViewState["gvResults_DataSource"];
// ViewState["gvResults_DataSource"] is container used to store the gv.DataSource ex: //ViewState["gvResults_DataSource"] = gridview_data.DataSource;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = sortExpression + " " + ConvertSortDirectionToSql(sortDirection);
gv.DataSource = dataView;
gv.DataBind();
}
}
protected void GridView_Data_Sorting(object sender, GridViewSortEventArgs e)
{
Sorting(GridView_Data,e.SortExpression, e.SortDirection);
}
Note: Please pay attention to add the function used for selecting data from database, or there won't be any data got in the gridview after select new page index, plus make sure your gridview's datasource is bind as table