获取ListView中所有RadioButtonLists的选定值

时间:2015-05-06 16:42:29

标签: c# asp.net listview radiobuttonlist ascx

我有一个ListView来创建几个RadioButtonList,然后我想在点击一个按钮后从每个RadioButtonList中获取所选的值。

    <asp:ListView ID="lvForm" runat="server">
        <ItemTemplate>
            <li>
                <asp:Label runat="server" Text='<%# Eval("Texto") %>' />
                <br />
                <asp:RadioButtonList runat="server">
                    <asp:ListItem Text="<%$ Resources:liSim.Text %>" Value="<%$ Resources:liSim.Text %>" />
                    <asp:ListItem Text="<%$ Resources:liNao.Text %>" Value="<%$ Resources:liNao.Text %>" />
                </asp:RadioButtonList>
            </li>
        </ItemTemplate>
        <ItemSeparatorTemplate />
        <LayoutTemplate>
            <ol style="list-style-type: upper-alpha;">
                <li id="itemPlaceholder" runat="server" />
            </ol>
        </LayoutTemplate>
    </asp:ListView>

<asp:Button runat="server" ID="btnSeguinte" Text="<%$ Resources:btnSeguinte.Text %>" OnClick="btnSeguinte_Click" />

最佳解决方案是在每个RadioButtonList上执行OnSelectedIndexChanged并在每次更改后保持保存。但是这种解决方法会在每次更改时强制进入服务器端。

如何在点击按钮后收集所有选定的值?

1 个答案:

答案 0 :(得分:0)

您应该能够简单地迭代ListView中的每个项目。首先,在ListView中命名您的RadioButtonList。这样可以更容易找到。

<asp:RadioButtonList ID="rbList" runat="server">
    <asp:ListItem Text="<%$ Resources:liSim.Text %>" Value="<%$ Resources:liSim.Text %>" />
    <asp:ListItem Text="<%$ Resources:liNao.Text %>" Value="<%$ Resources:liNao.Text %>" />
</asp:RadioButtonList>  

然后循环每个项目。在每个项目中找到RadioButtonList。获取您刚刚找到的RadioButtonList的SelectedValue,然后使用它,无论您喜欢。

protected void btnSeguinte_Click(object sender, EventArgs e)
{
    List<string> selectedValues = new List<string>();
    foreach(ListViewItem item in lvForm.Items)
    {
        RadioButtonList rb = (RadioButtonList)item.FindControl("rbList");

        // if none are selected, it returns an empty string
        if(rb.SelectedValue.length > 0)
        {
            selectedValues.Add(rb.SelectedValue);
        }
    }

    // do something with your selected values

}
相关问题