简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM