简体   繁体   English

在UserControl结构中按ID查找控件

[英]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. 我有许多UserControls,它是从一个父级继承的。

On the parent Page_Load , I want to find a specific control from the child UserControl and add it an Attributes . 在父Page_Load ,我想从子UserControl中找到一个特定的控件,并为其添加Attributes

The problem is I never know the structure of the child UserControl . 问题是我永远不知道子UserControl的结构。

I tried to use a recursive method to find the control by id : 我试图使用递归方法通过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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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