使用LINQ与组通过数据绑定中继器 [英] Databind repeater using Linq with group by
问题描述
我需要绑定分层数据转发如下:
I need to bind a repeater with hierarchical data as follows:
Category1
- Item1
- Item2
Category2
- Item3
- Item4
我目前的项目一个数据集,以及每个项目所属的类别。
I currently have a single dataset with the items as well as the category that each item belongs to.
我想学习LINQ和想知道是否有一种方法,我可以做使用LINQ一样吗?
I'm trying to learn Linq and was wondering if there was a way I can do the same using Linq?
下面是我的尝试:
var groupbyfilter = from dr in dtListing.AsEnumerable()
group dr by dr["Category"];
DataTable dtFinal = dtListing.Clone();
foreach (var x in groupbyfilter)
x.CopyToDataTable(dtFinal, LoadOption.OverwriteChanges);
rptList.DataSource = dtFinal;
rptList.DataBind();
但它麻烦的是它重复类别的每个项目。
But trouble with it is it repeats category for each item.
推荐答案
您需要嵌套在另一个中继器。
You'll need a repeater nested inside another.
做一个独特的 dtlisting
只选择类别字段。这个绑定到外部中继。
Do a distinct on the dtlisting
selecting only the category field. Bind this to the outer repeater.
在第二个中继器,选择数据的WHERE条件有类别字段,它等于正被数据绑定到中继器的设定值。你不得不处理这个在中继的 onitem_databound
事件。
In the 2nd repeater, select data whose where condition has category field which equals to the value that is being databound to the repeater item. You'd have to handle this in the repeater's onitem_databound
event.
下面是一个例子。
<%@ Import Namespace="System.Data" %>
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<div>
Category: <b><%# Container.DataItem%></b>
<asp:Repeater ID="Repeater2" runat="server">
<FooterTemplate>
<%="</ul>" %>
</FooterTemplate>
<HeaderTemplate>
<%= "<ul>"%>
</HeaderTemplate>
<ItemTemplate>
<li>
<%# ((Data.DataRow)Container.DataItem)[1] %>, <%# ((Data.DataRow)Container.DataItem)[0] %>
</li>
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
有关此示例中,我用一个CSV作为我的数据源,并用它创建了一个数据表。所以,我的codebehind是这样的:
For this sample I used a csv as my datasource, and created a datatable using it. So my codebehind looks like:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class _Default : System.Web.UI.Page
{
DataTable csvData;
protected void Page_Load(object sender, System.EventArgs e)
{
csvData = Utils.csvToDataTable("data.csv", true);
GridView1.DataSource = csvData;
GridView1.DataBind();
Repeater1.DataSource =
(from x in csvData.AsEnumerable() select x["category"]).Distinct();
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item |
e.Item.ItemType == ListItemType.AlternatingItem) {
Repeater rptr = (Repeater)e.Item.FindControl("Repeater2");
rptr.DataSource =
csvData.AsEnumerable().Where(x => x["category"].Equals(e.Item.DataItem));
rptr.DataBind();
}
}
}
这篇关于使用LINQ与组通过数据绑定中继器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!