Search code examples
c#asp.netuser-controlsfindcontrol

ASP.NET How to access a deeply nested user control on the parent page


I have a login control and at is nested 2 deep in a header control i.e Page --> Header Control --> Login Control. I cannot get a reference to the control on the page using FindControl. I want to be able to set the visible property of the control like

  if (_loginControl != null)
            _loginControl.Visible = false;

I ended up using a recursive FindControl method to find the nested control.

    public static Control FindControlRecursive(Control root, string id)
    {
        if (root.ID == id)
        {
            return root;
        }

        foreach (Control c in root.Controls)
        {
            Control t = FindControlRecursive(c, id);
            if (t != null)
            {
                return t;
            }
        }

        return null;
    }

Solution

  • Are you needing to disable/hide the User Control from the ASP.NET page it resides on (or does the User Control exist on a master page, say)? If it's in the same page, then in your ASP.NET page's code-behind you'd do:

    MyUserControlsID.Visible = false
    

    Where MyUserControl is the ID of your User Control. To determine the ID of your User Control look at the markup of your .aspx page and you will see something like this:

    <uc1:UserControlName ID="MyUserControlsID" runat="server" ... />
    

    Happy Programming!