【问题标题】:How can I traverse controls in a user control to find a certain control?如何遍历用户控件中的控件以找到某个控件?
【发布时间】:2023-03-14 10:08:01
【问题描述】:

ASP.NET 2.0 Web 表单

那么如何遍历用户控件中的所有控件并找到某种类型的控件并将事件附加到它?

我有一个类似的问题 How do I add a event to an ASP.NET control when the page loads? 处理添加事件 - 但如果我想找到一个控件,情况就不同了。

场景

控件是自定义控件:

<asp:Repeater runat="server" ID="options" OnItemDataBound="options_OnItemDataBound">
<HeaderTemplate>
    <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr>
</HeaderTemplate>
<ItemTemplate>
            <td>
                <span>
                    <asp:Label runat="server" ID="optionName">
                    </asp:Label>
                    <asp:DropDownList runat="server" ID="optionValues" CssClass="PartOption">
                    </asp:DropDownList>
                </span>
            </td>
</ItemTemplate>
<FooterTemplate>
        </tr>
    </table>
</FooterTemplate>
</asp:Repeater>

用户控件上的自定义控件声明:

<td><def:CustomControl id="somePartOptions" runat="server"></td>

在用户控件后面的代码中,我在 Page_Load 事件中尝试了以下操作:

    foreach(Control control in partOptions.Controls) {
            FindDropDownControl(control);
}

    protected void FindDropDownControl(Control controlContainer) {
        bool isRepeater = false;
        if (controlContainer is Repeater) {
            isRepeater = true;
        }

        if (controlContainer.HasControls()) {
            foreach (Control subControl in controlContainer.Controls) {
                FindDropDownControl(subControl);
            }
        }
    }

但是,布尔标志始终为假。那我在做什么?我最终想在中继器的 itemTemplate 中找到下拉列表控件,但我什至找不到中继器。

谢谢,

【问题讨论】:

标签: c# asp.net webforms


【解决方案1】:

我正在使用此方法获取容器中的控件列表(在每个嵌套级别上):

    public static List<Control> GetControlsByType(Control ctl, Type type)
    {
        List<Control> controls = new List<Control>();

        foreach (Control childCtl in ctl.Controls)
        {
            if (childCtl.GetType() == type)
            {
                controls.Add(childCtl);
            }

            List<Control> childControls = GetControlsByType(childCtl, type);
            foreach (Control childControl in childControls)
            {
                controls.Add(childControl);
            }
        }

        return controls;
    }

你可以这样使用t:

List<Control> repeaters = GetControlsByType(containerControl, typeof (Repeater));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2012-03-10
    • 2013-11-20
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多