Gytis39 Gytis39 - 1 year ago 92
C# Question

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

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

Answer Source

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";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download