HOW TO GET ALL CHILD CONTROLS OF A WINDOWS FORMS FORM OF A SPECIFIC TYPE (BUTTON/TEXTBOX)?

Ashish Pandey

Total Post:128

Points:898
Posted by  Ashish Pandey
C# 
C#
 1391  View(s)
Ratings:
Rate this:

I need to get all controls on a form that are of type x. I'm pretty sure I saw that code once in the past that used something like this:

dim ctrls() as Control

ctrls = Me.Controls(GetType(TextBox))

I know I can iterate over all controls getting children using a recursive function, but is there something easier or more straightforward, maybe like the following?

Dim Ctrls = From ctrl In Me.Controls Where ctrl.GetType Is Textbox

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

    Hi Ashish,

    This is an improved version of the recursive GetAllControls() that actually works on private vars:

        private void Test()

        {

             List<Control> allTextboxes = GetAllControls(this);

        }

        private List<Control> GetAllControls(Control container, List<Control> list)

        {

            foreach (Control c in container.Controls)

            {

                if (c is TextBox) list.Add(c);

                if (c.Controls.Count > 0)

                    list = GetAllControls(c, list);

            }

            return list;

        }

        private List<Control> GetAllControls(Control container)

        {

            return GetAllControls(container, new List<Control>());

        }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!