How to get the repeater-item in a Checkbox' Ch

2020-04-08 11:25发布

问题:

I have a CheckBox inside a Repeater. Like this:

<asp:Repeater ID="rptEvaluationInfo" runat="server">
    <ItemTemplate>
       <asp:Label runat="server" Id="lblCampCode" Text="<%#Eval("CampCode") %>"></asp:Label>
       <asp:CheckBox runat="server" ID="cbCoaching" value="coaching-required" ClientIDMode="AutoID" AutoPostBack="True" OnCheckedChanged="cbCoaching_OnCheckedChanged" />
    </ItemTemplate>
</asp:Repeater>

When some one clicks on the checkbox I want to get that entire row in my code behind. So if a CheckedChanged happens I want to get the Text of the Label lblCampCode in code behind.

Is it possible?

I have managed to write this much code.

protected void cbCoaching_OnCheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = (CheckBox)sender;
    Repeater rpt = (Repeater)chk.Parent.Parent;
    string CampCode = "";//  here i want to get the value of CampCode in that row
}

回答1:

So you want to get the RepeaterItem? You do that by casting the NamingContainer of the CheckBox(the sender argument). Then you're almost there, you need FindControl for the label:

protected void cbCoaching_OnCheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = (CheckBox)sender;
    RepeaterItem item = (RepeaterItem) chk.NamingContainer;
    Label lblCampCode = (Label) item.FindControl("lblCampCode");
    string CampCode = lblCampCode.Text;//  here i want to get the value of CampCode in that row
}

This has the big advantage over Parent.Parent-approaches that it works even if you add other container controls like Panel or Table.

By the way, this works the similar way for any databound web-control in ASP.NET (like GridView etc).