Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
sir, i have solution of question
Posted
Comments
deepak@10520046 15-Jan-14 4:45am    
so, you want to change the font style dynamically from code behind?

Try like this..


C#
private void Form1_Load(object sender, EventArgs e)
       {
           List<Control> allControls = GetAllControls(this);
           allControls.ForEach(k=>k.Font = new System.Drawing.Font ("Verdana",12));

       }


       private List<Control> GetAllControls(Control container, List<Control> list)
       {
           foreach (Control c in container.Controls)
           {

               if (c.Controls.Count > 0)
                   list = GetAllControls(c, list);
               else
                   list.Add(c);
           }

           return list;
       }
       private List<Control> GetAllControls(Control container)
       {
           return GetAllControls(container, new List<Control>());
       }
 
Share this answer
 
For an alternative to the usual, let's grab all the Controls using a Stack ... not doing recursion in the usual manner:
C#
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:
C#
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:
XML
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: [^].
 
Share this answer
 
Comments
Maciej Los 15-Dec-14 15:14pm    
+5
Here is one solution:
check here[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900