我怎样才能穿过控制在用户控件找到一定的控制? [英] How can I traverse controls in a user control to find a certain control?
问题描述
ASP.NET 2.0 Web表单
ASP.NET 2.0 Web forms
所以你怎么能透过用户控件的所有控件进行迭代,并查找某一类型的控制和事件追加到它?
So how can you iterate through all the controls in user control and find a certain type of control and append a event to it?
我有一个类似的问题<一href=\"http://stackoverflow.com/questions/5104377/how-do-i-add-a-event-to-an-asp-net-control-when-the-page-loads\">How我一个事件添加到ASP.NET控件在页面加载时与添加事件涉及 - 但这是,如果我想找到一个控制不同
I have a similar question How do I add a event to an ASP.NET control when the page loads? that deals with adding an event - but this is different if I wanted to find a control.
情景
控件是自定义控件:
<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>
在用户控件的自定义控件声明:
The custom control declaration on the user control:
<td><def:CustomControl id="somePartOptions" runat="server"></td>
在用户控件的背后code,我试着在Page_Load事件如下:
In the code behind of the user control, I tried the following in the Page_Load event:
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);
}
}
}
不过,布尔标志始终为false。所以,我在做什么?我最终想找到转发器的ItemTemplate中内DropDownList控件,但我甚至不能找到中继器。
However, the boolean flag is always false. So what am I doing? I am eventually wanting to find the dropdownlist control inside the itemTemplate of the repeater, but I can't even find the repeater.
感谢,
推荐答案
我用这个方法来获得容器控件列表(在每一层嵌套):
I'm using this method to get list of control in container (on each nesting level):
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:
You can use t in this way:
List<Control> repeaters = GetControlsByType(containerControl, typeof (Repeater));
这篇关于我怎样才能穿过控制在用户控件找到一定的控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!