I have been using this little piece of code to recursively search my control collections for a given control or type of controls and thought that it might be of some use to others. The general purpose utility code is here:
public static void SearchControls(ControlCollection controls, Action<Control> action)
{
foreach (Control control in controls)
{
if (control.HasControls())
{
SearchControls(control.Controls, action);
}
action(control);
}
}
For example, if you want to search for and Trim() all TextBox controls within a GridView, you could call the routine as follows using an anonymous method:
SearchControls(GridViewJobs.Controls, delegate(Control control)
{
TextBox textBox = control as TextBox;
if (textBox != null)
{
textBox.Text = textBox.Text.Trim();
}
});
If you need to search a GridView footer for a drop down list, you call the code as follows:
ControlUtility.SearchControls(gvwOrganizations.FooterRow.Controls, delegate(Control control)
{
DropDownList dropDownListCategory = control as DropDownList;
if (dropDownListCategory != null)
{
categoryID = int.Parse(dropDownListCategory.SelectedValue);
}
});