【问题标题】:Error binding DataAdapter->DataSet->LINQ->ASP.Net DataGrid绑定 DataAdapter->DataSet->LINQ->ASP.Net DataGrid 时出错
【发布时间】:2011-11-17 05:24:54
【问题描述】:

我有以下代码:

using (SqlConnection cn = new SqlConnection(Connection.Instance.ConnectionString))
{
    // Open the connection
    using (SqlCommand cmd = new SqlCommand())
    {
        try
        {
            cmd.Connection = cn;

            cmd.CommandText = "Select Customers.CustomerID, Addresses.AddressCode, Addresses.FirstName, Addresses.LastName, Addresses.Address1, Addresses.City, Addresses.State, " +
            "Addresses.Zip, Addresses.Home AS HomePhone, Addresses.Phone AS WorkPhone, Addresses.EmailAddress  From Customers " +
            "LEFT OUTER JOIN Addresses ON Addresses.ID=Customers.AddressID " +
            "Where CustomerType IN ('HomeOwner', 'Home Owner') AND Customers.ResellerID=@ResellerID ";

            cmd.Parameters.AddWithValue("@ResellerID", base.UserID);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet dsCustomer = new DataSet();
            da.Fill(dsCustomer);

            var customers = from c in dsCustomer.Tables[0].AsEnumerable().AsQueryable()
                            where c.Field<string>("CustomerID") == txtSearchCriteria.Text
                            select c;

            dgCustomers.CurrentPageIndex = 0;

            dgCustomers.DataSource = customers;
            dgCustomers.DataBind();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message + e.StackTrace);
        }
        finally
        {
            if ((cn != null) && (cn.State != ConnectionState.Closed))
                cn.Close();
        }
    }
}

这给了我错误

AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID 'dgCustomers' when AllowPaging is set to true and the selected data source does not implement ICollection.   at System.Web.UI.WebControls.DataGrid.CreateControlHierarchy(Boolean useDataSource)

如何转换此 LINQ 查询以使其可分页?

注意:这是我正在尝试做的简化版本。我知道在这个例子中我可以简单地修改 SQL 语句以包含“And CustomerID=@CustomerID”并完全绕过 LINQ。但是,从大局来看,我做不到。

【问题讨论】:

    标签: asp.net linq data-binding datagrid


    【解决方案1】:

    错误信息很清楚,您需要实现分页逻辑以利用分页。顺便说一句,要使您的代码正常工作,只需使用 ICollection 作为数据源,更改这一行:

    dgCustomers.DataSource = customers.ToList();
    

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2019-02-12
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多