在 C# 中使用 LINQ 的简单嵌套转发器示例

本文关键字:嵌套 简单 转发器 LINQ | 更新日期: 2023-09-27 18:32:27

所以我已经尝试并广泛搜索,但无法让我的嵌套中继器正常工作。

<asp:Repeater ID="rptrParent" runat="server">
<ItemTemplate>
    <dl class="StudentTasksList">
        <dt><%# Eval("ClassCode") %></dt>
        <asp:Repeater ID="rptrChild" runat="server">
            <ItemTemplate>
                <dd><%# Eval("Title") %></dd>
            </ItemTemplate>
        </asp:Repeater>            
    </dl>
</ItemTemplate>
</asp:Repeater>

C# 代码

        private void ListTasks()
    {
        using (StudentContext syndb = new StudentContext())
        {
            using (TaskContext dbdb = new TaskContext())
            {
                // Iterate through each active Class for the current Student finding any tasks not archived for this year
                var ClassTasks = (from c in syndb.GetClasses()
                                  where c.Students.Select(y => y.StudentID).Contains(LoggedInUserID)
                                  join t in dbdb.Tasks on c.ClassCode equals t.ClassCode
                                  where !t.Archive.HasValue || t.Archive.HasValue && t.Archive.Value && t.DueDate.Value.Year == DateTime.Now.Year
                                  group c by c.ClassCode);
                rptrParent.DataSource = ClassTasks;
                rptrParent.DataBind();
            }
        }
    }

因此,ClassCode 来自所选学生的 GetClasses() 方法,标题是在当前班级的任务联接中找到的任何标题的名称。 我需要的结果是学生的班级列表,每个 ClassCode 下都有任何相关的任务标题。 我已经尝试了几种不同的方法,所以这可能不是我尝试做的最佳样本。 如果有人能给我看一个填充嵌套转发器的联接 linq 查询的 LINQ C# 示例,我会很高兴,因为我找不到任何足够像样的东西来解决这个问题。

我还想知道如果类没有任何任务,如何填充 N/A,但我不会碰运气。

在 C# 中使用 LINQ 的简单嵌套转发器示例

若要填充内部转发器,必须像这样处理父转发器的 ItemDataBound 事件:

<asp:Repeater ID="rptrParent" runat="server" OnItemDataBound="rptrParent_ItemDataBound">

在后面的代码中

protected void rptrParent_ItemDataBound(object sender, RepeaterItemEventArgs e) {
    RepeaterItem item = e.Item;
    if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem)) {
        Repeater rptrChild = (Repeater)item.FindControl("rptrChild");
        rptrChild.DataSource = DataBinder.Eval(item.DataItem, "Group");
        rptrChild.DataBind();
    }
}

我猜您需要用作内部转发器数据源的数据项的属性在 LINQ 语句中分组时Group,但也许您需要更改它......

据我所知,LINQ 剂量在数据绑定中没有任何作用。您提到的 LINQ 查询看起来会查找并根据需要填充数据。但是你已经绑定了中继器,所以"rptrParent.DataBind();"将只绑定最外层的中继器。我认为您必须为"rptrParent"编写 ItemDataBound 事件,并找到子中继器控件,将其分配给您从 LINQ 查询中获得的组。

希望这对您有所帮助。