Reputation: 67
I've been looking for a while and i couldn't find anything that would help me with my problem, but sorry if i missed something.
So for school we had to learn VB and make a game, and i chose to make Sudoku. I found VB easy to understand so i decided to try a different language to see if it was the same. C# was my choice. I decided to start off by making the Sudoku game again and compare it to my VB game.
In the VB code i was able to make an array of all the textboxes that make up the 9x9 grid from the code:
For Y = 0 to 8
For X = 0 to 8
Grid(X, Y) = New Windows.Forms.TextBox
Pencil(X, Y) = New Windows.Forms.TextBox
With Grid(X, Y)
.BackColor = Grid(X, Y).BackColor
.Name = Asc(97 + X) & Y + 1
.Location = New System.Drawing.Point(35 + 50 * X + (FindBox(X) - 1) * 15, 50 + 50 * Y + (FindBox(Y) - 1) * 15)
.Size = New System.Drawing.Size(50, 50)
.Multiline = True
.MaxLength = 1
.Font = New Font(Grid(X, Y).Font.Name, Grid(X, Y).Font.Size + 10)
.TextAlign = HorizontalAlignment.Center
.TabIndex = (X + 1) + (Y * 9) + 1
.BorderStyle = BorderStyle.FixedSingle
End With
Me.Controls.Add(Grid(X, Y))
next
next
This meant i could easily refer to the Sudoku textbox's as a grid coordinate in the array. I attempted to replicate this in C# and ran into a problem almost instantly
public partial class Form1 : Form
{
TextBox[,] Grid = new TextBox[8,8];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int Y = 0; Y < 9; Y++)
{
for (int X = 0; X < 9; X++)
{
TextBox TBox = new TextBox();
Grid[X, Y] = TBox;
TBox.Location = new Point(50 + X * 100, 50 + Y * 50);
this.Controls.Add(TBox);
}
}
}
This code runs, but for some reason it only runs till Y = 7, then stops and does not loop any more times. This code works fine until i try to add anything that links the textbox's to the array (In this case Grid[X,Y] = TBox). I've tried it without using TBox (And just straight away using the array, but the same problem persists).
Just wondering if anyone can enlighten me as to why adding the line "Grid[X, Y] = TBox;" can completely ruin a nested for loop.
Thanks in advance, sorry if i didn't say enough/Said too much.
Upvotes: 0
Views: 112
Reputation: 6238
There is an important difference between C# and VB.NET in the context of arrays. Just a simple example. In C# the following array has exactly 10 elements and allowed indexes are from 0 to 9:
int[] array= new int[10];
In VB.NET the following array has 11 elements and allowed indexes are from 0 to 10:
Dim array(10) as Integer
You translated you code from VB.NET to C# without taking this difference into account and it is why you have problems. To fix this problem you should use:
TextBox[,] Grid = new TextBox[9,9];
Instead of:
TextBox[,] Grid = new TextBox[8,8];
Upvotes: 1
Reputation: 7618
It doesn't just stop.You get a IndexOutOfRangeException
Change this
new TextBox[8,8]
to this
new TextBox[9,9]
Or make the for loops "< 8"
Upvotes: 0