Loop through all controls of a Form, even those in GroupBoxes

后端 未结 9 1143
囚心锁ツ
囚心锁ツ 2020-11-29 05:17

I\'d like to add an event to all TextBoxes on my Form:

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms         


        
9条回答
  •  臣服心动
    2020-11-29 05:45

    Since the Question regarding "Adding an Event to your TextBoxes"; was already answered; I'm providing some explanation and adding an iteration alternative using a for loop instead.


    Problem:

    • Being Unable to Get Controls Inside a Container.


    Solution:

    • In order to retrieve the Controls inside a Container you have to specify the Container that Contains the Controls you wish to access to. Therefore your loop must check the Controls inside a Container.
      Otherwise your loop will not find the Controls inside a Container.

    i.e:

    foreach (Control control in myContainer.Controls)
    {
       if (control is TextBox) { /* Do Something */ }
    }
    
    • In case you have several Containers:
      Initially iterate the Containers.
      Then iterate over the controls inside the container (the container found in the initial iteration).


    Pseudo Code Example on How to use a for Loop Instead:

        ///  Iterate Controls Inside a Container using a for Loop. 
        public void IterateOverControlsIncontainer()
        {
            // Iterate Controls Inside a Container (i.e: a Panel Container)
            for (int i = 0; i < myContainer.Controls.Count; i++)
            {
                // Get Container Control by Current Iteration Index
                // Note:
                // You don't need to dispose or set a variable to null.
                // The ".NET" GabageCollector (GC); will clear up any unreferenced classes when a method ends in it's own time.
                Control control = myContainer.Controls[i];
    
                // Perform your Comparison
                if (control is TextBox)
                {
                    // Control Iteration Test.
                    // Shall Display a MessageBox for Each Matching Control in Specified Container.
                    MessageBox.Show("Control Name: " + control.Name);
                }
            }
        }
    

提交回复
热议问题