繁体   English   中英

在UserControl结构中按ID查找控件

[英]Find control by id in a UserControl structure

情况 (不是麦克):

我有许多UserControls,它是从一个父级继承的。

在父Page_Load ,我想从子UserControl中找到一个特定的控件,并为其添加Attributes

问题是我永远不知道子UserControl的结构。

我试图使用递归方法通过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);
}

这就是我从父母那里称呼它的方式:

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

但是我不工作。 我真的不确定这是否是实现我的目标的好方法。 请,我想知道您是否有任何建议或更好的方法。 非常感谢您的帮助。

如下更改您的查找方法

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