带有Repeater的RadioButtonList

时间:2016-11-18 20:21:03

标签: c# datarepeater

我在这里读了一篇非常好的文章:(使用DataList和Repeater Controls(C#)显示数据) https://www.asp.net/web-forms/overview/data-access/displaying-data-with-the-datalist-and-repeater/displaying-data-with-the-datalist-and-repeater-controls-cs

我试图回复文章作者,但我无法通过Facebook,Twitter等在工作中添加我的帐户来通过网站提出我的问题,所以我会问这里。

该示例非常详尽且易于理解,但我希望看到一个RadioButtonList(比如性别)x Male Female,显示DB字段值。 这对赞美文章内容是一个很大的帮助

THX

1 个答案:

答案 0 :(得分:0)

首先,您需要将RadioButtonList添加到DataListRepeater(它们的工作方式相同,因此我只提供一个示例)并添加OnItemDataBound事件

 <asp:DataList ID="DataList1" runat="server" OnItemDataBound="DataList1_ItemDataBound">
    <ItemTemplate>
        <asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
    </ItemTemplate>
</asp:DataList>

背后的代码

protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
    //find the control with findcontrol and cast back to a radiobuttonlist
    RadioButtonList radioButtonList = e.Item.FindControl("RadioButtonList1") as RadioButtonList;

    //add some listitems, usually filled from list or database
    for (int i = 0; i < 5; i++)
    {
        radioButtonList.Items.Insert(i, new ListItem("ListItem " + i, i.ToString(), true));
    }

    //cast the dataitem to the datarowview
    DataRowView row = e.Item.DataItem as DataRowView;

    //set the correct radiobuttonvalue
    radioButtonList.SelectedValue = row["dbValue"].ToString();
}