5

我的 aspx 中有一个中继器:

<asp:Repeater ID="rptDummy" runat="server" OnItemDataBound="rptDummy_OnItemDataBound"
     Visible="true">
</asp:Repeater>

在 web 的 c# 端,我编写了这个函数:

 protected void createRadioButtons(DataSet ds){
     List<System.Web.UI.WebControls.RadioButton> buttons = new List<System.Web.UI.WebControls.RadioButton>();
     foreach (DataTable dt in ds.Tables){
            foreach (DataRow r in dt.Rows){
               System.Web.UI.WebControls.RadioButton rb = new System.Web.UI.WebControls.RadioButton();
               rb.Text = r[1] + " " + r[2] + " " + r[3] + " " + r[4];
               rb.GroupName = (string)r[5];
               buttons.Add(rb);
            }
      }
      rptDummy.DataSource = buttons;
      rptDummy.DataBind();
 }

但是在尝试时,它什么也没显示。我究竟做错了什么?

4

2 回答 2

12

试试这个:

1 - 定义Repeater

<asp:Repeater ID="rptDummy" runat="server" OnItemDataBound="rptDummy_OnItemDataBound" >
    <ItemTemplate>
         <asp:RadioButtonList ID="rbl" runat="server" DataTextField="Item2" DataValueField="Item2" />
    </ItemTemplate>
</asp:Repeater>

2 - 构建数据结构并绑定转发器:

List<Tuple<string,string>> values = new List<Tuple<string,string>>();

foreach (DataTable dt in ds.Tables){
    foreach (DataRow r in dt.Rows){
       string text = r[1] + " " + r[2] + " " + r[3] + " " + r[4];
       string groupName = (string)r[5];
       values.Add(new Tuple<string,string>(groupName, text));
    }
}

//Group the values per RadioButton GroupName
rptDummy.DataSource = values.GroupBy(x => x.Item1);
rptDummy.DataBind();

3 - 定义OnItemDataBound事件:

protected void rptDummy_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        IGrouping<string, Tuple<string, string>> group = (IGrouping<string, Tuple<string, string>>)e.Item.DataItem;
        RadioButtonList list = (RadioButtonList)e.Item.FindControl("rbl");

        list.DataSource = group;
        list.DataBind();
    }
}

你看,每个都是IGrouping<string, Tuple<string, string>>指某个 GroupName 的一组 RadioButton,它们也是来自中继器的项目。对于每个项目,我们创建一个新的 RadioButtonList 代表整个 RadioButtons 组。

您可以通过使用与 a 不同的 DataStructure 使其变得更好,Tuple通常不清楚是什么Item1Item2意味着什么。

更新:

如果要查看选定的值:

protected void button_OnClick(object sender, EventArgs e)
{
    foreach (RepeaterItem item in rptDummy.Items)
    {
        RadioButtonList list = (RadioButtonList)item.FindControl("rbl");
        string selectedValue = list.SelectedValue;
    }
}
于 2013-03-03T20:16:40.110 回答
1

您应该放入RadioButton中继器并将其绑定到createRadioButtons事件中。

于 2013-03-03T19:34:48.893 回答