简体   繁体   English

读取Repeater内CheckBoxList的选中项

[英]Read checked items of CheckBoxList inside Repeater

Maybe a stupid question but I need some help on how to read checkbox values inside a repeater when posting a form. 可能是一个愚蠢的问题,但我需要一些有关发布表单时如何在直放站中读取复选框值的帮助。 I have a form and inside this form I have a Repeater and in each ItemTemplate I have a CheckBoxList. 我有一个表单,在此表单中,我有一个Repeater,在每个ItemTemplate中,我都有一个CheckBoxList。 This is my code a little bit simplified: 这是我的代码有点简化:

<form method="post">
    <asp:Repeater runat="server" ID="FormInputValues">
        <ItemTemplate>
            <asp:CheckBoxList runat="server" ID="CheckBoxValues"
                DataSource='<%# ((FormOptions)Container.DataItem).Options %>' />
        </ItemTemplate>
    </asp:Repeater>
    <br />
    <asp:LinkButton ID="SelectorNext" CssClass="button" OnClick="SelectorNext_Click"
        Text="Next" runat="server" />
</form>

My problem is that I need to be able to map all checked items in each CheckBoxList with its related data item. 我的问题是我需要能够将每个CheckBoxList中的所有选中项及其相关的数据项进行映射。 Something like this: 像这样:

Dictionary<"DataItem.ID", List<"CheckBox.Value">>

I can't figure out a good way to do this so if someone's got any suggestions I'll be very grateful! 我找不到解决此问题的好方法,因此,如果有人提出任何建议,我将不胜感激!

try with the code: 尝试使用代码:

for(int i = 0; i < FormInputValues.Items.Count; i++)
{
 CheckBoxList chklist = (CheckBoxList)FormInputValues.Items[i].FindControl("CheckBoxValues");
}

you will get every CheckBoxList in chklist object, you can traverse it to get selected checkboxes. 您将在chklist对象中获得每个CheckBoxList ,您可以遍历它以获取选定的复选框。

You can code like below to traverse CheckBoxList : 您可以像下面的代码那样遍历CheckBoxList

foreach (ListItem listItem in clbIncludes.Items)
{
    if (listItem.Selected) { 
    //do some work 
}
    else { 
    //do something else 
    }
}

where clbIncludes is a CheckBoxList 其中clbIncludes是一个CheckBoxList

You can use foreach loop just inside the for loop to achieve your required thing. 您可以在for循环内使用foreach循环来实现所需的功能。

Try this: 尝试这个:

Protected function repeater1_ItemCreated(Object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
      CheckBoxList checkBoxValues = (CheckBoxList)e.Item.FindControl("CheckBoxValues");
      String selectedValue = checkBoxValues.SelectedValue;
      //Do your stuff ...
    }
}

The ItemCreated event is the one you need, in there you can change how each repeater item looks. ItemCreated事件是您需要的事件,您可以在其中更改每个转发器项目的外观。

The other answer is also correct, but this example is more performant, as you do not need to loop through all repeater items and you do not need to loop through each checkbox in the CheckBoxList . 另一个答案也是正确的,但是此示例的性能更高,因为您不需要循环浏览所有重复器项目,也不需要循环遍历CheckBoxList每个复选框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM