gridview中的双向排序
本文关键字:排序 gridview | 更新日期: 2023-09-27 18:03:15
如何在GridView中实现双向排序,条件是我的GridView不绑定到SQL,而是绑定到datatable-column-row &数据集。
谢谢!
当你第一次绑定Datatable时,把它放在Viewstate中
gridView1.DataBind();
ViewState["dtbl"] = YourDataTable
这是代码,允许你这样做…
protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ViewState["dtbl"] as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
ComponentGridView.DataSource = dataView;
ComponentGridView.DataBind();
}
}
private string ConvertSortDirection(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
有关详细信息,请参阅MSDN文章GridView。排序 在您的数据绑定方法中,您将初始化viewstates,然后在排序事件中,您将执行以下操作:
void gvReport_Sorting(object sender, GridViewSortEventArgs e)
{
System.Data.DataTable dataTable = ViewState["dataTable"] as System.Data.DataTable;
string sortDirection = (ViewState["sortDirection"].ToString() == "ASC" ? "DESC" : "ASC");
ViewState["sortDirection"] = sortDirection;
if (dataTable != null)
{
System.Data.DataView dataView = new System.Data.DataView(dataTable);
dataView.Sort = String.Format("{0} {1}", e.SortExpression, sortDirection);
gvReport.DataSource = dataView;
gvReport.DataBind();
}
}