我有一个嵌套的转发器和一个内部的复选框,像这样
<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,所以我得到重复的值。有没有办法循环每个复选框并找到正确的值?
答案 0 :(得分:1)
为此,你必须在循环中定义一个字符串或字符串数组。
在这个答案中,我在一个字符串中给出解决方案。在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; }
}
}
}
}
答案 1 :(得分:0)
使用与外部循环相同的参数在内部循环中调用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;
}
}
}
}