For an alternative to the usual, let's grab all the Controls using a Stack ... not doing recursion in the usual manner:
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public static class SpecialMethods
{
public static IEnumerable<Control> GetAllControls(Control aControl)
{
Stack<Control> stack = new Stack<Control>();
stack.Push(aControl);
while (stack.Any())
{
var nextControl = stack.Pop();
foreach (Control childControl in nextControl.Controls)
{
stack.Push(childControl);
}
yield return nextControl;
}
}
}
If we wanted to set a specific Font for all Controls on a Form, we could use something like this in the Load Event of a Form:
Font theFont = new Font("Arial", 9.0F, FontStyle.Bold);
foreach(Control theControl in (SpecialMethods.GetAllControls(this)))
{
theControl.Font = theFont;
}
If we wanted to set only the Font of Button Controls:
foreach(Control theControl in (SpecialMethods.GetAllControls(this)).OfType<Button>().ToList())
{
theControl.Font = theFont;
}
Make sure the Form references Linq.
Sources: this post, in 2009, on StackOverFlow alerted me to the possibilities of using a Stack to make recursive traverses in .NET more efficient: [
^].
Be sure and see mrydengren's response: [
^], and Eric Lippert's response: [
^].