【问题标题】:Grid view Bind Problem when using List()使用 List() 时的网格视图绑定问题
【发布时间】:2011-09-18 09:20:21
【问题描述】:

.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

【问题讨论】:

  • 嗨,你解决了我的问题,但我无法理解的一件事 List Proinfo = new List(); Proinfo = (从 _NorthWindDataContext.Products 中的 p 选择新的 Productinformation { PID = p.ProductID, PName = p.ProductName, }).ToList(); gvFirst.DataSource = Proinfo .Take(5);然后需要转换这个 inlist
  • var Pro = from p in _NorthWindDataContext.Products 选择新产品信息 { PID = p.ProductID, PName = p.ProductName, }; gvFirst.DataSource = Pro.Take(5); gvFirst.DataBind();然后我不需要在两种情况下都在 ToList 中转换它 Take(5) return iEnurable ......请帮助我理解你给出的解决方案......
  • 如果您删除 AllowPaging 属性,您的两个代码版本都可以使用。

标签: c# asp.net linq gridview paging


【解决方案1】:

您必须使用ToList() 方法将列表返回到gvFirst。所以试试这个:

gvFirst.DataSource =  Proinfo.Take(PageSize).ToList();

解释

因为您在gvFirst 上设置了AllowPaging="true" 属性,所以分页可以用于任何实现ICollection 接口的数据源对象。

ProInfo.Take(PageSize) 返回一个IEnumerable,这就是你需要调用ToList() 方法的原因。

【讨论】:

    【解决方案2】:

    如果您在全球范围内将 Proinfo 声明为 ICollection

    private ICollection<Productinformation> Proinfo = null
    

    然后您使用 .Take 方法将结果作为不支持分页的可枚举,因此您必须将其转换为从 ICollection 继承的 List。

    gvFirst.DataSource =  Proinfo.Take(PageSize).ToList();
    

    【讨论】:

      猜你喜欢
      • 2016-06-05
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      相关资源
      最近更新 更多