1

Let's say i have this markup structure

<asp:Repeater id="rptItems" datasource="getItemsList()" runat="server" OnItemDataBound="rpAereos_ItemDataBound">
<ItemTemplate>
    <asp:Panel id="tableHolder" runat="server">
        <asp:table ID="TableHolded" runat="server">
                <asp:TableRow>
                        <asp:TableCell>
                            <asp:Panel runat="server" ID="panelToFind">Test</asp:Panel>
                        </asp:TableCell>
                    </asp:TableRow>
        </asp:table>
    </asp:Panel>
</ItemTemplate>
</asp:Repeater>

Now on ItemDataBound event I want to find the element panelToFind, but I don't want to go through all the elements to find this element like e.Item.FindControl("tableHolder").FindControl("tableHolded").AReallyLongCallChainUntilMyItem ... , I want to find anything under the tableHolder panel that has the id panelToFind, How would my ItemDataBound event look?

I would like to know if something like: e.Item.FindControl("tableHolder").FindAny("panelToFind")

Jonathan DS
  • 2,050
  • 5
  • 25
  • 48
  • 3
    Have you considered recursive `FindControl`? ASP.NET does not provide it, but there are a lot of implementations out there. – Andrei Aug 15 '13 at 12:46

1 Answers1

2

Declare an extension method like this:

public static class ControlExtensions
{

    public static IEnumerable<Control> GetEnumerableChildren(this Control control)
    {
        return control.Controls.Cast<Control>();
    }

    public static Control FindAny(this Control control, string id)
    {
        var result = control.GetEnumerableChildren().FirstOrDefault(c => c.ID == id);

        if (result != null)
            return result;

        return control.GetEnumerableChildren().Select(child => child.FindAny(id)).FirstOrDefault();
    }
}

Then do:

var foundControl = e.Item.FindControl("tableHolder").FindAny("panelToFind");

Note will return null if no control exists with that id.

Kevin Holditch
  • 5,165
  • 3
  • 19
  • 35