【问题标题】:how to bind result of GroupBy syntax in Linq to entities to grid view如何将 Linq 中 GroupBy 语法的结果绑定到实体到网格视图
【发布时间】:2013-11-19 18:25:34
【问题描述】:

我的数据库中有一个名为“Module_Menus_Menu”的表,表数据如下:

MenuID  ParentID    Name        URL
//===================================================
   1       0        Home        /Home
   2       0        Products    /Products
   3       0        Templates   /Templates
   4       2        Prod1       /Products/Cat1
   5       2        Prod2       /Products/Cat2
   6       3        Free        /Templates/Free
   7       3        Premium     /Templates/Premium

如您所见,这是我的菜单表和主页,产品、模板是一级菜单,Prod1 也在 products 和 prod2 下, 现在我想在网格视图(在管理区域)中显示它们只是为了列出它们 我想使用 GroupBy 语法来获取数据并像这样绑定网格视图:

Home

Products
Prod1
Prod2

Templates
Free
Premium

我搜索并找到了一个查询:

var items = (from m in context.Module_Menus_Menu group m by m.ParentID into g select new
                    {
                       ParentID = g.Key,
                       Name = g.Select(n => n.Name),
                       MenuID = g.Select(i => i.MenuID),
                       URL = g.Select(u => u.URL)
                    }).ToList();

现在当我将它绑定到网格视图时:

grdItems.DataSource = items;
grdItems.DataBind();

结果:

Name
System.Collections.Generic.List`1[System.String]    
System.Collections.Generic.List`1[System.String]    
System.Collections.Generic.List`1[System.String]

请帮帮我

【问题讨论】:

    标签: c# asp.net group-by linq-to-entities


    【解决方案1】:

    当结果为 Systems.Collections.Generic.List 时,数据绑定不知道将列表中的属性与哪一列相关联,因此获取类型为 List 的每一行。您需要在 gridview 中设置数据字段列。

        <columns>
          <asp:boundfield datafield="CustomerID" headertext="Customer ID"/>
          <asp:boundfield datafield="CompanyName" headertext="Company Name"/>
          <asp:boundfield datafield="Address" headertext="Address"/>
        </columns>
    

    【讨论】:

    • 问题不是这个,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多