Reputation: 3661
Trying to get all textbox values into 1d, 2d arrays
int[] xMatrix = new int[6], yMatrix = new int[6];
int[,] aMatrix = new int[6, 6], bMatrix = new int[6, 6], cMatrix = new int[6, 6];
foreach (Control control in this.Controls)
{
if (control is TextBox)
{
string pos = control.Name.Substring(1);
if (control.Name.StartsWith("a"))
{
int matrixPos = Convert.ToInt32(pos);
int x = matrixPos / 10;
int y = matrixPos % 10;
aMatrix[x, y] = Convert.ToInt32(control.Text);
}
else if (control.Name.StartsWith("b"))
{
int matrixPos = Convert.ToInt32(pos);
int x = matrixPos / 10;
int y = matrixPos % 10;
bMatrix[x, y] = Convert.ToInt32(control.Text);
}
else if (control.Name.StartsWith("c"))
{
int matrixPos = Convert.ToInt32(pos);
int x = matrixPos / 10;
int y = matrixPos % 10;
cMatrix[x, y] = Convert.ToInt32(control.Text);
}
else if (control.Name.StartsWith("x"))
{
int arrayPos = Convert.ToInt32(pos);
xMatrix[arrayPos] = Convert.ToInt32(control.Text);
}
else if (control.Name.StartsWith("y"))
{
int arrayPos = Convert.ToInt32(pos);
yMatrix[arrayPos] = Convert.ToInt32(control.Text); // <== ERROR LINE
}
}
Getting error message
And here are given values
What am I missing?
Upvotes: 1
Views: 2235
Reputation: 4481
There seems to be some TextBox (or derived Control) with name starting with "y6"-"y9". Checking your ...designer.cs file should help to find that one.
Or you could leave that dangerous road to use your variable names for storing parameters. Instead you could use the Tag-Property of your TextBoxes to store the corresponding coordinates. This will make things clearer and less vulnerable.
Upvotes: 0
Reputation: 150108
When this line runs:
int arrayPos = Convert.ToInt32(pos);
it probably results in arrayPos being 6 (guess with insufficient data).
Arrays are 0 based, meaning valid indices for your arrays are 0 to 5. I bet your controls are named 1 to 6...
If that is the case, subtract 1 from arrayPos to convert from the range 1..6 to the range 0..5.
int arrayPos = Convert.ToInt32(pos) - 1;
Upvotes: 1
Reputation: 223257
I think you are getting value in arrayPos >= 6
, that is why you are getting this exception because yMatrix
is defined as an array of 6 elements.
int arrayPos = Convert.ToInt32(pos);
Here pos is from string pos = control.Name.Substring(1);
, put a debugger and see what value you are getting in pos
.
Upvotes: 2