c# - 填充 ASP.NET 转发器

标签 c# asp.net radio-button

我的 aspx 中有一个转发器:

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

在网络的 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();
 }

但是试了一下,什么都没有。 我做错了什么?

最佳答案

试试这个:

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 - 构建数据结构并绑定(bind)转发器:

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的一组RadioButtons,它们也是repeater中的item。我们为每个项目创建一个新的 RadioButtonList,它代表整组 RadioButton。

您可以通过使用与 Tuple 不同的 DataStructure 来使其变得更好, 通常不清楚是什么 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;
    }
}

关于c# - 填充 ASP.NET 转发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189805/

相关文章:

C# IS 运算符不能用于 lambda 表达式?

c# - 中继器链接按钮 Onclick 未触发

C#:MS Excel 中复选框的状态

c# - 使用 C# 将文本文档分成多个部分

c# - mysql的asp.net角色创建问题

JQuery 和 RadioButtons 问题

html - 当我已经在使用 ng-model 和 ng-value 时,我想用后面的数据检查我的单选按钮

c# - 在特定线程上运行工作

c# - ASP.Net 图表 X 轴显示误导性日期标签

user-interface - 取消选择单选按钮