Suppose I have 10 textBox (textBox1, textBox2, ... textBox10). As when pressing a button, using a loop, take a value from each textBox and continue to use.

And if the textBox names are different for me, for example (square, perimeter, amount, size, radius ...) and all these names in the array, how will I address each of them in turn and take the value from each.

  • How to loop through the array you know? If so, it remains only to contact the textBox by name. How to do this is written here: ru.stackoverflow.com/questions/564289/… - default locale
  • Thanks, I know about cycles, I only needed to know how to access the element by its name. - Ilya Serykh
  • one
    There is another way - once to initialize your array with these elements and work with the array - Anton Shchyrov
  • Do you work with WinForms? - Alex Krass
  • Yes, with WinForm, but I already figured out - Ilya Serykh

2 answers 2

 string[] num = { "textBox1", "textBox2", "textBox3" }; int sum = 0; for (int i = 0; i < num.Length; i++) { var textBox = this.Controls[num[i]]; sum += Convert.ToInt16(textBox.Text); } MessageBox.Show("Сумма введенных чисел = " + Convert.ToString(sum)); 
  • 3
    Why not create an array of Textboxes right away? - Andrei NOP
  • @AndreyNOP because out of 100 fields for counting, I only use 10 for certain values, some are written to a file, and the rest are used for other operations. therefore, we need different arrays, those 10 Boxes are in the array - totalBox, those that are written to the file - fileBox, the others - otherBox - Ilya Serykh

Cycle ForEach go through TextBox'am and get the necessary data.

 var val = ""; foreach (Control x in this.Controls) { if (x is TextBox) { val += ((TextBox)x).Text; } }