To illustrate the usefulness of control arrays, I'll work with the magic squares example from pages 301306 of my book Visual Basic .NET Primer Plus (Sams, 2003, ISBN 0672324857). Figure 1 shows a screen shot from the Magic Squares program. When the program starts, the user is expected to fill in the matrix size to be used. For Figure 1, I entered 3, thus generating a 3x3 matrix. It's called a magic squares matrix because the row, column, and main diagonal elements of the matrix all sum to the same value ("magic number"). In Figure 1, the magic number is 15.
Matrices with odd element sizes use a considerably simpler algorithm than those with even element sizes. Because of this complexity, I've restricted the program to odd matrix sizes.
The code limits the size of the matrix to 9x9 and checks that the user has entered an odd number falling within the prescribed range. I limited the size of the matrix simply because that size fits conveniently on the form; you can easily change it if you want to play with a larger matrix. Figure 2 shows a 9x9 magic squares matrix, with the magic number 369.
Figure 1 A 3x3 magic squares matrix.
Figure 2 A 9x9 magic squares matrix.
Most of the code is straightforward, but I'll discuss the code that specifically applies to the control arrays used in the program.