GridView控件在不使用数据源控件时,实现排序和分页

有时你想在不使用数据源控件如SqlDataSourceObjectDataSource控件的情况下绑定GridView控件到数据,这意味着排序和分页将不会借助数据源控件被自动处理,为了实现排序和分页,你必须要处理GridView控件的PageIndexChangingSorting事件,如下例所示:

 

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = SortDataTable(GetYourDataSource(), true);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
 
  
private stringGridViewSortDirection
{
get { returnViewState["SortDirection"] as string ?? "ASC"; }
set { ViewState["SortDirection"] = value; }
}
 
private stringGridViewSortExpression
{
get { returnViewState["SortExpression"] as string ?? string.Empty; }
set { ViewState["SortExpression"] = value; }
}
 
private stringToggleSortDirection()
{
switch (GridViewSortDirection)
{
case"ASC":
GridViewSortDirection = "DESC";
break;
case"DESC":
GridViewSortDirection = "ASC";
break;
}
returnGridViewSortDirection;
}
 
protectedDataView SortDataTable(DataTable dataTable, boolisPageIndexChanging)
{
if (dataTable != null)
{
DataView dataView = newDataView(dataTable);
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format("{0} {1}",  GridViewSortExpression,GridViewSortDirection);
}
else
{
dataView.Sort = string.Format("{0} {1}",GridViewSortExpression,ToggleSortDirection());
}
}
returndataView;
}
else
{
return newDataView();
}
}
 
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
intpageIndex = GridView1.PageIndex;
GridView1.DataSource = SortDataTable(GetYourDataSource(), false);
GridView1.PageIndex = pageIndex;
GridView1.DataBind();
}

你可能感兴趣的:(GridView)