Gytis39 Gytis39 - 6 months ago 39
C# Question

How can I address textboxes in windows forms by their number? [SOLVED]

So I want to have around 12 text boxes (later on I will also add 12 picture boxes below) that will have the name of the product in them. However, while there is no option for there to be more than 12 products in the catalog, there can be less.

To save space, I thought I will create a cycle, that checks every loop if there are products left in the catalog, and if there is, it assigns the product to a textbox[i].

So basically, I would like to be able to address textBox1 as textBox[1], textBox2 as textBox[2] and so on.

I tried doing it like

System.Windows.Forms.TextBox[] array = { textBox1, textBox2, textBox3 };

But it seems like I can only create such an object in from initialization, and when created there it seems to be unacessible anywhere else, even in the same form, so I can call the function to display only once when the form is initialized, and I would like to call the display method every time someone buys anything

EDIT: Thank you, my issue has been solved. The user tinstaafl provided exactly what I was looking for. Thank you all for your answers. My biggest issue was not how to fit textBoxes into array, but rather how to access them by their number, so I could automatize working with them by accessing the certain textBox by indexer of a cycle. And the problem with an array was that I could only create it in

public Form1()
//System.Windows.Forms.TextBox[] array = { textBox1, textBox2, textBox3 };

here. And then I could not access it from anywhere else but here. If I tried to create it someone else, I would get an error.


If your textboxes are numbered consistently you access them through the Controls property of the form or container they're in. You can use their name directly:

for(int i = 0; i<12;i++)
     this.Controls["textBox"+i.ToString()].Text = "Something";