2012-07-06 118 views
1

试图让所有的文本框的值到一维,二维阵列指数超出范围异常错误

http://content.screencast.com/users/TT13/folders/Jing/media/7689e48c-9bd6-4e22-b610-656b8d5dcaab/2012-07-06_0347.png

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 
        } 
} 

收到错误消息

enter image description here

,这里是给定的值

enter image description here

我错过了什么?

回答

2

我认为你在arrayPos >= 6中获得价值,这就是为什么你会得到这个例外,因为yMatrix被定义为一个由6个元素组成的数组。

int arrayPos = Convert.ToInt32(pos); 

这里pos是从string pos = control.Name.Substring(1);,把一个调试器,看看有什么价值你得到的pos

+0

好吧,我需要使所有数组+1 +1大。因为它们从0开始而不是1 – heron 2012-07-06 05:26:51

+0

不,不要使数组1变大,使索引1变小。否则你浪费了第一个数组元素,索引0.请参阅我的答案以了解代码更改。 – 2012-07-06 05:28:07

1

当此行运行:

int arrayPos = Convert.ToInt32(pos); 

它可能导致arrayPos为6(有数据不足猜测)。

数组是基于0的,这意味着你的阵列的有效索引是0到5我敢打赌,你的控件被命名为1至6 ...

如果是这样的情况下,从arrayPos从转换减去1范围1..6到范围0..5。

int arrayPos = Convert.ToInt32(pos) - 1; 
0

似乎有一些TextBox(或派生控件)的名称以“y6” - “y9”开头。 检查你的... designer.cs文件应该有助于找到那个。

或者你可以让这条危险的道路使用你的变量名来存储参数。相反,您可以使用文本框的标签属性来存储相应的坐标。这会让事情变得更加清晰,不易受到伤害。