问题
I have a repeater and I am trying to access the Checkbox controller from the LinkButton event.The Repeater controls only contain the literals and linkbuttons but not checkbox controls.
<asp:Repeater ID="rptTicketsInPerformance" OnItemDataBound="rptTicketsInPerformance_ItemBound" runat="server">
<ItemTemplate>
<asp:CheckBox ID="cbticketSelect" runat="server" />
<asp:Literal ID="ltticketDescription" runat="server" />
</ItemTemplate>
<FooterTemplate>
<div class="change-buttons">
<asp:LinkButton ID="btDonate" runat="server" CssClass="button-primary" Text="Donate" OnClick="donateButton_click" />
<asp:HyperLink ID="hlCancel" runat="server" CssClass="button-primary close-reveal-modal" Text="Cancel" />
</div>
</FooterTemplate>
</asp:Repeater>
Code Behind
protected void donateButton_click(object sender, System.EventArgs e)
{
RepeaterItem items = ((sender as LinkButton).Parent as RepeaterItem);
foreach(var itm in items.Controls)
{
if(itm is CheckBox)
{
// Do something here
}
}
}
回答1:
You can loop all the Repeater items and use FindControl to locate the CheckBox in each item.
protected void donateButton_Click(object sender, EventArgs e)
{
string checkedBoxes = "";
foreach (RepeaterItem item in rptTicketsInPerformance.Items)
{
CheckBox cb = item.FindControl("cbticketSelect") as CheckBox;
checkedBoxes += cb.Checked.ToString() + ", ";
}
Label1.Text = checkedBoxes;
}
回答2:
You should note that the Parent of the sender is actually the Repeater, not the Repeater item.
So, you should point to
sender.Parent.Items
and then iterate over those, and find the CheckBox.
回答3:
Try this to FindControl:
protected void donateButton_click(object sender, System.EventArgs e)
{
RepeaterItem items = ((sender as LinkButton).Parent as RepeaterItem);
foreach (RepeaterItem itm in items.Controls)
{
CheckBox chk = (CheckBox)itm.FindControl("cbticketSelect");
if (chk.Checked)
{
Lable1.Text = "Do something ";
// Do something here
}
}
}
来源:https://stackoverflow.com/questions/44641078/get-checkbox-object-from-a-repeater