How to get a reference to a control from its' string name in C#?
Asked
Active
Viewed 2,032 times
2 Answers
9
If the Control is nested, use Control.FindControl
from the parent Control. Otherwise, you'll have to write your own FindControlRecursive
-
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