1

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

ahmed
  • 14,316
  • 30
  • 94
  • 127

2 Answers2

9

Page.FindControl

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
davogones
  • 7,321
  • 31
  • 36
  • Note: In collections of controls, the FindControl method will return a different instance of the control of that name. In ASP.NET, that control will have a unique name also. In other words, FindControlRecursive will return the 1st control of that name. – oglester Jan 30 '09 at 04:45
1
        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);
        }
NateMpls
  • 268
  • 1
  • 7