在事件上从中继器检索同级控件

joh*_*hnc 1 c# repeater

我在中继器控件上有一个 DropDownList 以及一个按钮。

当我想启用该按钮时,该按钮将被禁用,直到在 DropDownList 上选择了一个有效的项目。不幸的是,我似乎无法做到。

通过以下方式找到转发器:(.As() 方法是 (object as T) 的扩展方法,只是使转换更容易)

sender.As<Control>().NamingContainer.Parent.As<Repeater>()
Run Code Online (Sandbox Code Playgroud)

然而,我回来的中继器对我没有帮助,因为 FindControl(string name) 函数没有返回任何东西 - 并且在观察窗口中没有显示任何有用的东西。

那么,如何从转发器上另一个项目的事件(在本例中为 DropDown_SelectedIndexChanged)在转发器上获取同级控件(在本例中为 ImageButton)?

编辑

我终于解决了

sender.As<ImageButton>().NamingContainer.As<RepeaterItem>().FindControl("ControlName")
Run Code Online (Sandbox Code Playgroud)

net*_*tos 5

我想我有你的问题的答案:

1.-我用下拉列表和按钮创建了一个中继器来进行测试:

 <asp:Repeater ID="rp" runat="server">
   <ItemTemplate>
        <asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>
        <asp:ListItem>3</asp:ListItem>
        <asp:ListItem>4</asp:ListItem>
        <asp:ListItem>5</asp:ListItem>
        <asp:ListItem>6</asp:ListItem>

        </asp:DropDownList>
        <asp:ImageButton ID="Button1" runat="server" Enabled="False" />
        </ItemTemplate>
        </asp:Repeater>
Run Code Online (Sandbox Code Playgroud)

我对中继器进行数据绑定。

2.-我创建了 DropDownList1_SelectedIndexChanged 方法:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList control = (DropDownList)sender;

        RepeaterItem rpItem = control.NamingContainer as RepeaterItem;
        if (rpItem != null)
        {
            ImageButton btn = ((ImageButton)rpItem.FindControl("Button1"));
            btn.Enabled = true;

        }

    }
Run Code Online (Sandbox Code Playgroud)

这样做的方法是询问控件,谁是它的父级,也就是说,RepeaterItem,或者您可以使用 NamingContainer(正如我最后写的那样),然后您可以询问内部的任何控件。