簡體   English   中英

如何在RadioButtonList中使用Repeater來重復RadioButtonList的ListItem

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

首先,可以使用帶中繼器的中繼器嗎? 如果是,那么在以下情況下如何使用嵌套轉發器。

<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

中繼器綁定

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

每個問題的選項都保存在數據庫中,最小選項可以為3,最大選項可以為6。如何在rp_Question中使用另一個轉發器來重復每個問題的選項。 我想展示這樣的表情。

在此處輸入圖片說明

不幸的是,您不能在asp:RadioButtonList內使用轉發器。 它只允許使用ListItem 您會得到一個錯誤,即轉發器是一個未知的元素。 但是您可以在后面的代碼中綁定asp:RadioButtonList

擴展KateCute給出的答案,您可以為此使用ItemDataBound事件。

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

然后在代碼后面。

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