BaseForm method to loop through all controls

BenTam-3003 686 Reputation points
2022-07-14T08:00:24.903+00:00

Dear All,

I am trying to create a BaseForm. Thus in the future, each Form project's Forms will inherit from this BaseForm. I create a method, ResizeForm, that the Resize event will call this method. This method is going to loop through all controls in the inherited form to do something.

Could anybody tell me that can the method loops through all controls?

220731-baseform.gif

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2022-07-14T08:06:12.023+00:00

    In Winforms, it is

    this.Controls  
    

    but not with System.Windows.Controls.Control, which is WPF

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-07-14T11:24:15.003+00:00

    If there a panels or other similar containers consider the following.

    public static class ControlExtensions  
    {  
        public static IEnumerable<T> Descendants<T>(this Control control) where T : class  
        {  
            foreach (Control child in control.Controls)  
            {  
                if (child is T thisControl)  
                {  
                    yield return (T)thisControl;  
                }  
      
                if (child.HasChildren)  
                {  
                    foreach (T descendant in Descendants<T>(child))  
                    {  
                        yield return descendant;  
                    }  
                }  
            }  
        }  
    }  
    

    Implemented

    public partial class BaseForm : Form  
    {  
        public BaseForm()  
        {  
            InitializeComponent();  
            Resize += OnResize;  
        }  
      
        private void OnResize(object sender, EventArgs e)  
        {  
            var controls = this.Descendants<Control>();  
            foreach (var control in controls)  
            {  
                Console.WriteLine($"{control.Parent.Name}.{control.Name}");  
            }  
        }  
    }  
    

    Full source


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.