我在ASP.NET 4的C-sharp上工作.
我需要向GridView中的列添加排序函数。我已经将AllowSorting-property在GridView上设置为true,并将排序表达式添加到列中。
不幸的是,排序在GridView中不起作用。
下面是应该能够排序的列的代码隐藏文件,但是我得到了错误。
'System.Data.DataView.DataView(System.Data.DataTable)‘的最佳重载方法匹配有一些无效的参数
在这条线上:
DataView sortedView = new DataView(BindData());代码背后:
string sortingDirection;
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"] ?? "Name";
}
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(RetrieveProducts());
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(RetrieveProducts());
sortedView.Sort = SortField + " " + sortingDirection;
gvProducts.DataSource = sortedView;
gvProducts.PageIndex = e.NewPageIndex;
gvProducts.DataBind();
}
private void BindData()
{
gvProducts.DataSource = RetrieveProducts();
gvProducts.DataBind();
}
private DataSet RetrieveProducts()
{
DataSet dsProducts = new DataSet();
string sql = " ... ";
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
cn.Open();
using (OdbcCommand cmd = new OdbcCommand(sql, cn))
{
........
}
}
return dsProducts;
}编辑#1
DataView sortedView = new DataView(dsProducts.Tables[0]);编辑# 2
我在aspx页面添加了以下内容:
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />但是,如果在列名中单击,则会出现以下新错误:
System.IndexOutOfRangeException: Cannot find table 0.在这条线上:
Line 100: DataView sortedView = new DataView(dsProducts.Tables[0]);发布于 2015-07-29 08:07:01
DataView类只有三个构造函数,其中一个是默认构造函数DataView(),第二个是以DataTable作为参数DataView(DataTable),另一个是四个参数DataView(DataTable、String、String、DataViewRowState)。
DataView构造函数期望这些类型中的任何一个参数,但是您的代码有其他类型的参数。这就是错误。
BindData方法应该返回一个DataTable对象,
//This function should return a Datatable
private void BindData()
{
gvProducts.DataSource = RetrieveProducts();
gvProducts.DataBind();
}你可以把它传递到你的DataView里。
DataView sortedView = new DataView(BindData());用于第二次编辑,
System.IndexOutOfRangeException: Cannot find table 0.在这条线上:
Line 100: DataView sortedView = new DataView(dsProducts.Tables[0]);我猜数据集是空的,错误清楚地说明在0位置的数据集中没有任何表。因此,请检查您的数据集是否有表。可能是您的sql请求没有得到任何表来填充数据集。否则,您可能已经创建了dataset的新实例。
https://stackoverflow.com/questions/31694087
复制相似问题