如何在子Repeater的ItemCommand事件中获取当前的Repeater

时间:2017-08-02 03:06:41

标签: c# asp.net nested-repeater

这是HTML代码:

    <asp:Repeater ID="Repeater1" runat="server"
    OnItemDataBound="Repeater1_ItemDataBound">
    <ItemTemplate>
        <h1>Repeater 1</h1>
        <asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="Repeater2_ItemDataBound">
            <ItemTemplate>
                <h1>Repeater 2</h1>
               <asp:LinkButton CommandArgument='<%#Container.ItemIndex%>' CommandName="cmdDeleteItem" ID="lnkDelete" runat="server" >Delete</asp:LinkButton>
            </ItemTemplate>
        </asp:Repeater>
    </ItemTemplate>
</asp:Repeater>

这是代码背后:

protected void Repeater2_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "cmdDeleteItem":
                {
                    var Repeater2= (Repeater)e.Item.FindControl("Repeater2");
                    var list = new ArrayList(Repeater2.Items);
                    list.Add(Repeater2.Items.Count);
                    Repeater2.DataSource = list;
                    Repeater2.DataBind();
                }
                break;
        }
    }

Repeater2_ItemCommand事件可能无法找到自己的Repeater(Repeater2)。

1 个答案:

答案 0 :(得分:2)

您无法使用FindControl方法。在这种情况下,您应该将源参数强制转换为Repeater,如下所示:

var Repeater2 = (Repeater)source;

然后您可以访问转发器的所有属性,即item_command事件被触发。