当我想手动对GridView进行排序时,我收到此错误:gridview sort System.Web.dll中出现未处理的“System.StackOverflowException”类型异常
这是我运行的代码行。 “Melder”是我想要排序的列的正确名称。
gvOutlookMeldingen.Sort("Melder", SortDirection.Ascending);
提前谢谢。
答案 0 :(得分:3)
您必须处理PageIndexChanging和Sorting事件“
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = SortDataTable(GetYourDataSource(), true);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
private string GridViewSortDirection
{
get { return ViewState["SortDirection"] as string ?? "ASC"; }
set { ViewState["SortDirection"] = value; }
}
private string GridViewSortExpression
{
get { return ViewState["SortExpression"] as string ?? string.Empty; }
set { ViewState["SortExpression"] = value; }
}
private string ToggleSortDirection()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
{
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression,GridViewSortDirection);
}
else
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression,ToggleSortDirection());
}
}
return dataView;
}
else
{
return new DataView();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = GridView1.PageIndex;
GridView1.DataSource = SortDataTable(GetYourDataSource(), false);
GridView1.PageIndex = pageIndex;
GridView1.DataBind();
}
答案 1 :(得分:2)
第一次绑定时将数据表置于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文章http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
答案 2 :(得分:0)
当我遇到同样的问题时,我偶然发现了你的问题。
在做了一些研究并阅读了关于Sort方法的MSDN帮助后,我想问你是否在GridView的Sorting事件中调用了这个方法(我做过)?
这是错误的方法,因为Sort方法再次调用Sorting事件,这将导致无限循环。
我不知道为什么,但Sort()应该只在Sorting事件之外工作。