gpt4 book ai didi

c# - 填充 ASP.NET 转发器

转载 作者:太空狗 更新时间:2023-10-29 22:16:27 28 4
gpt4 key购买 nike

我的 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com