如何从转发器中的CheckBoxList中提取已检查的项目?

时间:2013-06-06 14:12:22

标签: vb.net linq repeater checkboxlist

我有一个转发器“语句”,其构造如下:

<asp:Repeater ID="Statements" runat="server"><ItemTemplate><ul>
    <li>
        <div>
            <asp:Label Text='<%#("Problem Statement: " + Eval("Statement"))%>' runat="server"></asp:Label></div>
        <div>
            <asp:Label Text='<%#("Goal: " + Eval("Goal"))%>' runat="server"></asp:Label></div>
        <asp:CheckBoxList ID="Objectives" runat="server" RepeatDirection="Horizontal" RepeatColumns="2">
        </asp:CheckBoxList>
    </li>
</ul>
</ItemTemplate>
</asp:Repeater>

我试图从重复的CheckBoxList中提取所有已检查的项目,但到目前为止,没有运气。下面给出了一个无效的强制转换错误,但我的其他尝试也导致了失败。如何使用LINQ从重复列表中提取所有选中的项?

Dim list = _
  (From c As Control In Me.FindControl("Statements").Controls _
  Where c.GetType() Is GetType(CheckBoxList) _
  Select c).ToList()

Dim selected = _
  From c As CheckBoxList In list.AsEnumerable() _
  Select c.Items.AsQueryable().Cast(Of ListItem).Select(Function(l) l.Selected = True)

提前致谢。

2 个答案:

答案 0 :(得分:3)

您可以旋转语句转发器的RepeaterItem并使用linq获取所有选中的复选框(仅限AlternatingItem和Item类型)。

        Dim lstAllSelected As New List(Of ListItem)

        Statements.Items.ForEach(Sub(rpi As RepeaterItem)
                                     If rpi.ItemType = ListItemType.AlternatingItem OrElse rpi.ItemType = ListItemType.Item Then
                                         Dim lstNewItems As List(Of ListItem) = (From li As ListItem In CType(rpi.FindControl("Objectives"), CheckboxList).Items _
                                                                                 Where li.Selected).ToList()
                                         If Not lstNewItems Is Nothing AndAlso lstNewItems.Count > 0 Then
                                             lstAllSelected.AddRange(lstNewItems)
                                         End If
                                     End If
                                 End Sub)

答案 1 :(得分:1)

这将为您提供每个转发器项目中选定ListItem的列表。

Dim selected = (From itm As RepeaterItem In Statements.Items
            From li As ListItem In DirectCast(itm.FindControl("Objectives"), CheckBoxList).Items
            Where li.Selected
            Select li).ToList