2012-07-06 151 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文件應該有助於找到那個。

或者你可以讓這條危險的道路使用你的變量名來存儲參數。相反,您可以使用文本框的標籤屬性來存儲相應的座標。這會讓事情變得更加清晰,不易受到傷害。