This may help you:
public Control RecursiveFind(Control ParentCntl, string NameToSearch)
{
if (ParentCntl.ID == NameToSearch)
return ParentCntl;
foreach (Control ChildCntl in ParentCntl.Controls)
{
Control ResultCntl = RecursiveFind(ChildCntl , NameToSearch);
if (ResultCntl != null)
return ResultCntl;
}
return null;
}
Another approach
------------------
myForm.FindControl<Label>("myLabel");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyExtensions
{
public static class Extensions
{
public static IEnumerable<T> FindControl<T>(this Control parentControl, String name = "")
{
if (parentControl is T)
{
if (String.IsNullOrWhiteSpace(name))
yield return (T)(object)parentControl;
else if (parentControl.Name.Equals(name))
{
yield return (T)(object)parentControl;
yield break;
}
}
var filteredControlList = from controlList in parentControl.Controls.Cast<Control>()
where controlList is T || controlList.Controls.Count > 0
select controlList;
foreach (Control childControl in filteredControlList)
{
foreach(T foundControl in FindControl<T>(childControl, name))
{
yield return foundControl;
if (!String.IsNullOrWhiteSpace(name))
yield break;
}
}
}
}
}
this.Controls["name"];
This is the actual code that is ran:
public virtual Control this[string key]
{
get
{
if (!string.IsNullOrEmpty(key))
{
int index = this.IndexOfKey(key);
if (this.IsValidIndex(index))
{
return this[index];
}
}
return null;
}
}
vs:
public Control[] Find(string key, bool searchAllChildren)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key", SR.GetString("FindKeyMayNotBeEmptyOrNull"));
}
ArrayList list = this.FindInternal(key, searchAllChildren, this, new ArrayList());
Control[] array = new Control[list.Count];
list.CopyTo(array, 0);
return array;
}
private ArrayList FindInternal(string key, bool searchAllChildren, Control.ControlCollection controlsToLookIn, ArrayList foundControls)
{
if ((controlsToLookIn == null) || (foundControls == null))
{
return null;
}
try
{
for (int i = 0; i < controlsToLookIn.Count; i++)
{
if ((controlsToLookIn[i] != null) && WindowsFormsUtils.SafeCompareStrings(controlsToLookIn[i].Name, key, true))
{
foundControls.Add(controlsToLookIn[i]);
}
}
if (!searchAllChildren)
{
return foundControls;
}
for (int j = 0; j < controlsToLookIn.Count; j++)
{
if (((controlsToLookIn[j] != null) && (controlsToLookIn[j].Controls != null)) && (controlsToLookIn[j].Controls.Count > 0))
{
foundControls = this.FindInternal(key, searchAllChildren, controlsToLookIn[j].Controls, foundControls);
}
}
}
catch (Exception exception)
{
if (ClientUtils.IsSecurityOrCriticalException(exception))
{
throw;
}
}
return foundControls;
}