I have a nested repeater and a check box inside that, Like this
<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>
And I have button outside this repeater, On this button click event I want to get all the values of that check box. I have tried some thing like this,
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);
}
Now the problem is that, This code always finds first CheckBox only, So i get repeated values. IS there any way to loop through each check box and find correct values?
You call FindControlRecursive in the inner loop with the same parameters as outer loop. That's the problem?
var cbInterest = (CheckBox)FindControlRecursive(repeatedInterest , "cbInterest");
the full code:
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;
}
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments