Gytis39
Gytis39

Reputation: 37

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

Upvotes: 0

Views: 519

Answers (4)

Mohit S
Mohit S

Reputation: 14064

Create a global variable of array or list

System.Windows.Forms.TextBox[] TxtArray;

Then after initalization in your form constructor

InitializeComponent();

You can add up the line like

TxtArray = new TextBox[] { textBox1, textBox2, textBox3, ... };

Upvotes: 0

AarónBC.
AarónBC.

Reputation: 1330

If you already have the 12 textboxes added at design time you can do this:

public partial class Form1 : Form
{
    List<TextBox> textboxes; //As a member of the class to be accesible everywhere in the class.
    public Form1()
    {
        InitializeComponent();
        textboxes = new List<TextBox> { textBox1, textBox2, textBox3, ... }; //Just to be sure they are already created.
    }

And then you can acces to them by their index in the list textboxes[i] from any method of your form class.

Upvotes: 0

tinstaafl
tinstaafl

Reputation: 6948

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";
}

Upvotes: 0

Davatar
Davatar

Reputation: 156

What about using a List?

List<TextBox> textboxes = new List<TextBox> { textBox1, textBox2, textBox3 };

For this you'll need a reference to System.Collections.Generic.

After that you can access the textboxes with their number in the list:

textboxes[0]

Upvotes: 1

Related Questions