Search code examples
c#asp.netrepeater

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. I want to show out put like this.

enter image description here


Solution

  • Expanding on the answer KateCute gave, you can use the ItemDataBound event for that.

    <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));
        }
    }