C# 对listview中的现有项进行排序

C# 对listview中的现有项进行排序,c#,asp.net,listview,webforms,C#,Asp.net,Listview,Webforms,我正在尝试对我拥有的listview中的项进行排序,这些项将从listviews ASPX声明中的SelectMethod填充到listview中 <asp:ListView ID="productList" runat="server" DataKeyNames="ProductID" GroupItemCount="4" ItemType="StoreTest.Models.Product" SelectMethod="GetProdu

我正在尝试对我拥有的listview中的项进行排序,这些项将从listviews ASPX声明中的SelectMethod填充到listview中

<asp:ListView ID="productList" runat="server" 
            DataKeyNames="ProductID" GroupItemCount="4"
            ItemType="StoreTest.Models.Product" SelectMethod="GetProducts" >

出现此问题的原因是,您正在尝试ASPX中的声明性绑定SelectMethod以及代码绑定productList.DataSource=query。当您使用SelectMethod绑定时,您使用的是声明性绑定,而声明性绑定又是您的模型绑定—您显示的异常表明了相同的情况


我建议您也通过代码进行初始绑定,可能是在页面加载时,并删除SelectMethod。这样,您的两个方法都将使用代码绑定,这应该可以工作。

在注释ordering switch语句时是否会出现相同的错误?@Peter Yes,我会,无论哪种方式,我已经在ASPX代码中绑定了一次数据。您能在ASPX代码中共享您正在绑定的代码吗?@praveen pulose ASPX的代码在我问题的顶部,getProducts方法的代码在底部。谢谢praveen,我在看到你的留言之前就想出来了,做了同样的事。谢谢你的帮助。
        productList.Items.Clear();
        var _db = new StoreTest.Models.SiteContext();
        IQueryable<Product> query = _db.Products;
        switch(sortList.SelectedValue)
        {
            case "Price Asc":
                query = query.OrderBy(o=> o.UnitPrice);
                break;
            case "Price Des":
                query = query.OrderByDescending(o => o.UnitPrice);
                break;
            case "Name Asc":
                query = query.OrderBy(o => o.ProductName);
                break;
            case "Name Des":
                query = query.OrderByDescending(o => o.ProductName);
                break;
            case "Product ID Asc":
                query = query.OrderBy(o => o.ProductID);
                break;
            case "Product ID Des":
                query = query.OrderByDescending(o => o.ProductID);
                break;
        }
            productList.DataSource = query;
            productList.DataBind();
public IQueryable<Product> GetProducts([QueryString("id")] int? categoryID)
    {
        var _db = new StoreTest.Models.SiteContext();
        IQueryable<Product> query = _db.Products;
        if (categoryID.HasValue && categoryID > 0)
        {
            query = query.Where(p => p.CategoryID == categoryID);
            Session["categoryid"] = categoryID;
        }
        return query;
    }
    public IQueryable<Product> GetProducts()
    {
        int categoryID = -1;
        if(Request.QueryString["id"]!=null)
        {
            categoryID = Convert.ToInt32(Request.QueryString["id"]);
        }
        var _db = new StoreTest.Models.SiteContext();
        IQueryable<Product> query = _db.Products;
        if (categoryID!=-1 && categoryID > 0)
        {
            query = query.Where(p => p.CategoryID == categoryID);
            Session["categoryid"] = categoryID;
        }
        return query;
    }
productList.DataSource = query.ToList();
        productList.DataBind();