Reputation: 3702
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?
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.
SCENARIO
The control is a custom 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>
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);
}
}
}
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.
thanks,
Upvotes: 2
Views: 1490
Reputation: 9834
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;
}
You can use t in this way:
List<Control> repeaters = GetControlsByType(containerControl, typeof (Repeater));
Upvotes: 2