使用List()时网格视图绑定问题
本文关键字:视图 绑定 问题 网格 List 使用 | 更新日期: 2023-09-27 18:08:50
.aspx:
<asp:GridView ID="gvFirst" runat="server" AutoGenerateColumns="false"
AllowPaging="true"
ondatabound="gvFirst_DataBound" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ProductID"/>
<asp:BoundField DataField="Name" HeaderText="ProductName" />
</Columns>
<PagerTemplate>
<asp:Panel ID="pnlPager" runat="server">
</asp:Panel>
</PagerTemplate>
</asp:GridView>
cs:
public class Productinformation
{
public int PID
{
get;
set;
}
public string PName
{
get;
set;
}
}
using (NorthWindDataContext _NorthWindDataContext = new NorthWindDataContext())
{
Proinfo = new List<Productinformation>();
Proinfo = (from p in _NorthWindDataContext.Products
select new Productinformation
{
PID = p.ProductID,
PName = p.ProductName,
}).ToList();
gvFirst.DataSource = Proinfo.Take(PageSize) ;
gvFirst.DataBind();
}
Proinfo
变量被全局声明。现在,当我运行这段代码时,它显示了以下错误:
数据源不支持服务器端数据分页
如果我使用变量的var类型,那么它是工作的,但是我们不能全局声明变量的var类型,所以如果我使用它,那么我就必须每次在分页中调用这个方法。我不想用Objectdatasource
必须使用ToList()
方法返回List给gvFirst
。所以试试这个:
gvFirst.DataSource = Proinfo.Take(PageSize).ToList();
解释:
因为在gvFirst
上设置了属性AllowPaging="true"
,所以分页可以与任何实现ICollection
接口的数据源对象一起使用。
ProInfo.Take(PageSize)
返回一个IEnumerable
,这就是为什么你需要调用ToList()
方法。
如果全局声明Proinfo为iccollection
private ICollection<Productinformation> Proinfo = null
然后你使用。take方法,你得到的结果是一个不支持分页的可枚举对象,所以你必须将其转换为继承iccollection的List。
gvFirst.DataSource = Proinfo.Take(PageSize).ToList();