Vinc 웃
Vinc 웃

Reputation: 1247

Find control by id in a UserControl structure

The situations (Not mike the douchebag) :

I have a multitudes of UserControls it inherit from one parent.

On the parent Page_Load, I want to find a specific control from the child UserControl and add it an Attributes.

The problem is I never know the structure of the child UserControl.

I tried to use a recursive method to find the control by id :

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

    return root.Controls.Cast<Control>()
       .Select(c => FindControlRecursive(c, id))
       .FirstOrDefault(c => c != null);
}

And this is how I call it from the parent:

Page page = HttpContext.Current.Handler as Page;
var mycontrol = FindControlRecursive(page, "id_x");
if (mycontrol != null)
{
     string test = "";
}

But I don't work. I am really not sure if this is a good way to achieve my goal. Please, I want to know if you have any suggestions or better way to do it. Your help will be highly appreciated.

Upvotes: 0

Views: 1984

Answers (1)

Damith
Damith

Reputation: 63065

change your find method as below

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
        return root;

    foreach (Control control in root.Controls)
    {
        Control found = RecursiveFindControl(control, id);
        if (found != null)
            return found;
    }

    return null;
}

Upvotes: 1

Related Questions