Search code examples
c#.netwinformsfindcontrol

Find multiple controls in a windows form application using Control.ControlCollection.Find when the name of the control is changing


I am a beginner to c# and windows forms. I want to use Controls.ControlsCollection.Find to find multiple textboxes (present in groupboxes) in the form. (Please note that the groupboxes are loaded dynamically during runtime using a button in the form).

I have used for loop to vary the name of the control(TextBox) to find(Tb{a}). Then I use foreach loop to access the controls in the array.

I tried using for loop to vary the name of the textbox. I was expecting it to create a control array with those textboxes. Later, I will convert the value to float and add it to 'L'

private float FindTextBoxes()
{
     for (int i=1; i < a+1; i=i+2)
     {
         Control[] textboxes = this.Controls.Find($"Tb{i}",true);
     }
     float L = 0;
     foreach (Control ctrl in textboxes)
     {
         if (ctrl.GetType() == typeof(TextBox))
          {
              L = L + float.Parse(((TextBox)ctrl).Text);
          }
     }           
     return L;
}

The error I am getting is: Error CS0103 The name 'textboxes' does not exist in the current context. How to fix this?

All help is appreciated. Thank you.


Solution

  • The variable has to be defined outside of the loop.

        private float FindTextBoxes()
        {
            List<TextBox> textboxes = new List<TextBox>();
            float L = 0;
            for (int i=1; i < a+1; i=i+2)
            {
                textboxes.AddRange(Controls.Find($"Tb{i}",true).OfType<TextBox>());
            }
    
            foreach (TextBox ctrl in textboxes)
            {
                L += float.Parse(ctrl.Text);
            }           
            return L;
        }