Creating Control Arrays
Control arrays are a very useful functionality in your application. They tend to simplify things that you are doing to a certain number of controls. For example, you want to disable a numerous number of textboxes, you wouldn’t have to code each textbox for disabling, instead you would just use a loop for disabling these certain controls.
In the Visual Basic 6.0 era, creating control arrays are just a snap. Creating controls with the same name would automatically array your controls. But in the .Net era you cannot just do this by the fly (on your Design mode). So, how could you do this? I will present 3 ways of achieving this, being the last way as the most efficient way.
The first approach is the crudest of them all. In this solution you intend to really create an array of controls. For the reason of demonstrating, let’s try creating an array of 50 textbox controls.
TextBox[] textboxes = new TextBox[50];
for (int i = 0; i < 50; i++) {
textboxes[ i].Width = 100;
…
}
The problem as you see here is that you will manually place the controls in your form. Which would be quite problematic especially if you want to place controls which are not so relevant with each other.
The second approach is to traverse the controls collection of the form. This is a very effective solution. But the problem is you’ll have to always check the name and type of the control if it matches the controls you want to traverse as seen in this code:
foreach ( Control c in this.Controls) {
if (c.GetType().ToString() == “System.Windows.Forms.TextBox” && c.Name == “myName”) {
….
}
}
The third and final solution is my preferred approach to this problem. First is you’ll have to name your controls in series. It means that your control names must have numeric values assigned to it. Think of it as an index for your control. Ex:
TextBox1, TextBox2, TextBox3, …
After that, you can now loop using the controls collection. But instead of looping with all of the controls lets directly get the name:
for (int i = 0; i < 50; i++) {
TextBox txt = (TextBox) this.Controls[“TextBox” + i.ToString()];
Txt.Enabled = false;
…
}
Well, as you can see the third solution is pretty simple and straight forward. No name verifications are required and at the same time you can also use your design mode to place your controls on the form. The only drawback I can see with this approach is you could not name your control to its exact descriptive names. But I think it’s quite a little sacrifice imaging the lines of code that you’ll save with this approach.