简体   繁体   English

如何在RadioButtonList中使用Repeater来重复RadioButtonList的ListItem

[英]How to use Repeater inside RadioButtonList to repeat ListItem of RadioButtonList

First, Can repeater with in a repeater be used? 首先,可以使用带中继器的中继器吗? If yes than how I can use nested repeater in following scenario. 如果是,那么在以下情况下如何使用嵌套转发器。

<div class="row">
    <asp:Repeater ID="rp_Question" runat="server">
        <ItemTemplate>
            <p class="_100">
                <h2 id="h4_Question" runat="server"><%# Eval("question_text") %></h2>
            </p>
            <p class="left">
                <asp:RadioButtonList ID="rb_Question" runat="server">
                    <asp:ListItem Text="Option1" Value="1"></asp:ListItem>
                    <asp:ListItem Text="Option2" Value="2"></asp:ListItem>
                    <asp:ListItem Text="Option3" Value="3"></asp:ListItem>
                    <asp:ListItem Text="Option4" Value="4"></asp:ListItem>
                </asp:RadioButtonList>
            </p>
        </ItemTemplate>
    </asp:Repeater

Repeater Binding 中继器绑定

rp_Question.DataSource = _question.GetAll();
rp_Question.DataBind();

The options of each question are saved in database, minimum option could be 3 and maximum could be 6. How can I use an other repeater inside rp_Question to repeat options of each question. 每个问题的选项都保存在数据库中,最小选项可以为3,最大选项可以为6。如何在rp_Question中使用另一个转发器来重复每个问题的选项。 I want to show out put like this. 我想展示这样的表情。

在此处输入图片说明

Unfortunately, you can't use repeater inside asp:RadioButtonList . 不幸的是,您不能在asp:RadioButtonList内使用转发器。 It allows only ListItem inside. 它只允许使用ListItem You will get an error, that repeater is a not known element. 您会得到一个错误,即转发器是一个未知的元素。 But you can bind asp:RadioButtonList in code behind. 但是您可以在后面的代码中绑定asp:RadioButtonList

Expanding on the answer KateCute gave, you can use the ItemDataBound event for that. 扩展KateCute给出的答案,您可以为此使用ItemDataBound事件。

<asp:Repeater ID="rp_Question" runat="server" OnItemDataBound="rp_Question_ItemDataBound">

And then in code behind. 然后在代码后面。

protected void rp_Question_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    //find the radiobuttonlist with findcontrol and cast back to it's original type
    RadioButtonList rb_Question = e.Item.FindControl("rb_Question") as RadioButtonList;

    //get the current datarow
    DataRowView row = e.Item.DataItem as DataRowView;

    //get the id from the datarow object
    string questionID = row["question_id"].ToString();

    //get the answers from the db with questionID and bind them as listitems just like in the loop below

    //just a loop to add some listitems for demo
    for (int i = 0; i < 5; i++)
    {
        rb_Question.Items.Insert(i, new ListItem("Option " + i.ToString(), i.ToString(), true));
    }
}

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

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