无法在嵌套中继器中找到复选框
本文关键字:复选框 中继器 嵌套 | 更新日期: 2023-09-27 17:50:07
我有一个嵌套的重复器和一个复选框在里面,像这样
<asp:Repeater ID="rptInterestCategory" runat="server" OnItemDataBound="rptInterestCategory_ItemDataBound" >
<ItemTemplate>
<asp:Repeater ID="rptInterests" runat="server" OnItemDataBound="rptInterests_ItemDataBound">
<ItemTemplate>
<asp:CheckBox ID="cbInterest" runat="server" OnCheckedChanged="cbInterest_CheckedChanged" Data-Id='<%# DataBinder.Eval(Container.DataItem, "id") %>' Text='<%# DataBinder.Eval(Container.DataItem, "name") %>' />
</ItemTemplate>
</asp:Repeater>
<hr/>
</ItemTemplate>
</asp:Repeater>
我在这个中继器外面有一个按钮,在这个按钮点击事件中,我想获得那个复选框的所有值。我试过这样做,
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (RepeaterItem repeated in rptInterestCategory.Items)
{
var rptInterests = (Repeater)FindControlRecursive(repeated, "rptInterests");
foreach (RepeaterItem repeatedInterest in rptInterests.Items)
{
var cbInterest = (CheckBox)FindControlRecursive(repeated, "cbInterest");
if (cbInterest.Checked)
{
name = cbInterest.Text;
}
}
}
}
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
现在的问题是,这段代码总是只找到第一个CheckBox,所以我得到重复的值。是否有任何方法循环遍历每个复选框并找到正确的值?
为此,您必须在循环外定义一个字符串或字符串数组。
在这个答案中,我给出了一个字符串的解决方案。在String s
中,您将获得所有选中的复选框值和单独的符号^
在button_click
上,只需输入我的代码,您将获得所有选定的CheckBox
值。
string s = "";
foreach (RepeaterItem item in rptInterestCategory.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
Repeater dl = (Repeater)item.FindControl("rptInterests");
foreach (RepeaterItem dli in repeatedInterest.Items)
{
if (dli.ItemType == ListItemType.Item || dli.ItemType == ListItemType.AlternatingItem)
{
var checkBox = (CheckBox)dli.FindControl("cbInterest");
if (checkBox.Checked) { s += (s == "") ? checkBox.Text : "^" + checkBox.Text; }
}
}
}
}
在内部循环中使用与外部循环相同的参数调用FindControlRecursive。这就是问题所在?
var cbInterest = (CheckBox)FindControlRecursive(repeatedInterest , "cbInterest");
完整代码:
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (RepeaterItem repeated in rptInterestCategory.Items)
{
var rptInterests = (Repeater)FindControlRecursive(repeated, "rptInterests");
foreach (RepeaterItem repeatedInterest in rptInterests.Items)
{
var cbInterest = (CheckBox)FindControlRecursive(repeatedInterest , "cbInterest");
if (cbInterest.Checked)
{
name = cbInterest.Text;
}
}
}
}