如何从C#中的'字符串名称获取对控件的引用

时间:2021-01-07 23:38:10

How to get a reference to a control from its' string name in C#?

如何从C#中的'字符串名称获取对控件的引用?

2 个解决方案

#1


Page.FindControl

If the Control is nested, use Control.FindControl from the parent Control. Otherwise, you'll have to write your own FindControlRecursive

如果Control是嵌套的,请使用父Control中的Control.FindControl。否则,您将不得不编写自己的FindControlRecursive

#2


        private Control FindControlRecursive(Control root, string id)
        {
            return root.ID == id
                       ? root
                       : (root.Controls.Cast<Control>()
                             .Select(c => FindControlRecursive(c, id)))
                             .FirstOrDefault(t => t != null);
        }

#1


Page.FindControl

If the Control is nested, use Control.FindControl from the parent Control. Otherwise, you'll have to write your own FindControlRecursive

如果Control是嵌套的,请使用父Control中的Control.FindControl。否则,您将不得不编写自己的FindControlRecursive

#2


        private Control FindControlRecursive(Control root, string id)
        {
            return root.ID == id
                       ? root
                       : (root.Controls.Cast<Control>()
                             .Select(c => FindControlRecursive(c, id)))
                             .FirstOrDefault(t => t != null);
        }