How to get a reference to a control from its'

2019-08-15 20:06发布

问题:

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

回答1:

Page.FindControl

If the Control is nested, use Control.FindControl from the parent Control. Otherwise, you'll have to write your own 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);
        }