Apr 13, 2007

Recursive Find Control Code

  1 public T FindControl<T>(string id) where T : Control
2 {
3 return FindControl<T>(Page, id);
4 }
5
6 public static T FindControl<T>(Control startingControl, string id) where T : Control
7 {
8 // this is null by default
9 T found = default(T);
10
11 int controlCount = startingControl.Controls.Count;
12
13 if (controlCount > 0)
14 {
15 for (int i = 0; i < controlCount; i++)
16 {
17 Control activeControl = startingControl.Controls[i];
18 if (activeControl is T)
19 {
20 found = startingControl.Controls[i] as T;
21 if (string.Compare(id, found.ID, true) == 0) break;
22 else found = null;
23 }
24 else
25 {
26 found = FindControl<T>(activeControl, id);
27 if (found != null) break;
28 }
29 }
30 }
31 return found;
32 }

kick it on DotNetKicks.com

No comments: