0

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.

Paras
  • 15
  • 4

1 Answers1

1

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;
    }
MrSpt
  • 499
  • 3
  • 16
  • Hello @ MrSpt, The above code works. But I wish to know if elements of a listbox have indices to them?, as I also have access a particular textbox in the collection as well. – Paras Mar 03 '23 at 09:23
  • You should create a separate question for that. – MrSpt Mar 03 '23 at 10:10
  • Okay, I will take note of that. For this question, if I want to access the listbox in another method, do I have to declare the listbox as a field? Please help with this @MrSpt. – Paras Mar 03 '23 at 11:39
  • Yes with a field or property. Regarding your second question maybe this post helps you. https://stackoverflow.com/questions/6504336/get-the-value-for-a-listbox-item-by-index – MrSpt Mar 03 '23 at 12:08