Sometimes, it's a great idea to create an array if similar controls. It eliminates the need of having individual variable/member names, allows for traversing the array in a loop, and a lot more. Using the designer, if you have many controls, often means manual code, repeating the same stupid clicks, etc. This is the opposite to the main idea of programming. The designer use should be limited for very specific ad-hoc programming. Real serious software is created using more of the code. Please see my comment to Solution 1.
So, to start with, don't create your text boxes in the designer. This is not a best way to create an array.
Where to put it? It's totally up to you. You should know that if you declare an object in the class, all
instance members (that is, non-static ones) of the class will have access to it. Where to initialize? In many places, but the array could be initialized at the point of declaration, and the elements could be initialized in some method called from the constructor (along with designer-generated
InitializeComponents
, if any):
const int textBoxCount =
TextBox[] myTextBoxes = new TextBox[textBoxCount];
Now, you need to initialize the elements in the loop. Let's assume you call it from constructor (but you can do it elsewhere):
void InitializeMyTextBoxes(Control someParent) {
for (int index = 0; index < textBoxCount; ++index) {
myTextBoxes[index] = new TextBox();
myTextBoxes[index].Width =
myTextBoxes[index].Left =
myTextBoxes[index].Width =
myTextBoxes[index].Parent = someParent;
}
}
This way, you can access all elements of the array through the array object,
myTextBoxes
.
—SA