I have created 100 textboxes programmatically using the following code:
for (int c = 0; c < 100; c++)
{
TextBox tb = new TextBox();
tb.Text = "ADI" + i;
tb.Click += new EventHandler(b_Click);
Point p = new Point(20, 30 * i);
tb.Location = p;
this.panel1.Controls.Add(tb);
i++;
}
Now I want to retrieve/add some data to them.
Example:
textBox1.Text = "a";
but the program doesn't recognize textBox1
, because actually it doesn't exist.
How can I solve it?
The WinForms designer and you use Partial classes. You work on one part of the class. The Designer on another. And at compile time, what you each wrote is put together. The designer created code is run with the call of InitializeComponents().
Accordingly, the designer can do nothing that you could not also do. It also creates stuff "Dynamic at runtime".
In this case the solution is fairly simple - store references to those Boxes as you create them:
//class scope variable
TextBox[] createdBoxes = new TextBox[100];
//wichever function you run that in
for (int c = 0; c < 100; c++)
{
TextBox tb = new TextBox();
//Position code omited for readability
createdBoxes[c] = tb;
}
There is one caveat however: Do not store information in the GUI classes. It is a rather common mistake of using that array of TextBoxes you created to store the data. That will only make retreiving and re-setting that data unessesarily hard. Consider storing the Data in code behind, making the GUI classes merely a representation of the game state.
Also with that many TextBoxes, you are propably deep in XY Problem territory.