【发布时间】: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 中找到下拉列表控件,但我什至找不到中继器。
谢谢,
【问题讨论】: