我需要在 GridView 中的列中添加排序功能。
我已将GridView上的 AllowSorting-property 设置为 true ,并将排序表达式添加到列中。
<asp:BoundField DataField="doName" HeaderText="doName" SortExpression="doName" />
不幸的是,排序并没有在GridView中运行。
以下是应该能够排序的列的代码隐藏文件,但是我收到错误:
异常详细信息:System.IndexOutOfRangeException:找不到列 doName。
代码背后:
string sortingDirection;
DataSet dsProducts = new DataSet();
DataTable dt1 = new DataTable();
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
public string SortField
{
get
{
return (string)ViewState["SortField"] ?? "doName";
}
set
{
ViewState["SortField"] = value;
}
}
protected void gvProducts_Sorting(object sender, GridViewSortEventArgs e)
{
sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(dt1);
sortedView.Sort = e.SortExpression + " " + sortingDirection;
SortField = e.SortExpression;
gvProducts.DataSource = sortedView;
gvProducts.DataBind();
}
protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (dir == SortDirection.Ascending)
{
sortingDirection = "Asc";
}
else
{
sortingDirection = "Desc";
}
DataView sortedView = new DataView(dt1);
sortedView.Sort = SortField + " " + sortingDirection;
gvProducts.DataSource = sortedView;
gvProducts.PageIndex = e.NewPageIndex;
gvProducts.DataBind();
}
private void BindData()
{
gvProducts.DataSource = RetrieveProducts();
gvProducts.DataBind();
}
private DataSet RetrieveProducts()
{
sql = "Select * from doTable;";
dsProducts = new DataSet();
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
adapter.Fill(dsProducts);
dt1 = new DataTable();
dsProducts.Tables.Add(dt1);
}
}
return dsProducts;
}
答案 0 :(得分:2)
发生此异常是因为在gvProducts_PageIndexChanging
方法中,dt1
的值已重置为新DataTable()
,但它没有任何行或列。
所以你必须重新加载dt1.
更改您的代码如下。
OdbcDataAdapter adapter = new OdbcDataAdapter(cmd);
adapter.Fill(dsProducts);
if (dsProducts.Tables.Count > 0)
{
dt1 = dsProducts.Tables[0];
}
dtProducts = dt1;
-------------------------------------------
protected void gvProducts_Sorting(object sender, GridViewSortEventArgs e)
{
sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
BindData();
DataView sortedView = new DataView(dt1);
sortedView.Sort = e.SortExpression + " " + sortingDirection;
SortField = e.SortExpression;
gvProducts.DataSource = sortedView;
gvProducts.DataBind();
}