2011-02-14 128 views
1
 int i = amount; //amount will always start at 0 
     int j = i + 1; 

     GroupBox[] verGroup; 
     verGroup = new GroupBox[i]; 

     verGroup[i].Name = "verGroup" + i.ToString(); 
     verGroup[i].Width = 400; 
     verGroup[i].Height = 120; 
     verGroup[i].Left = 5; 
     verGroup[i].Top = 5 + (verGroup[i].Height * i) + (10 * i); 
     verGroup[i].Text = "Verification #" + j.ToString(); 

     pnlVer.Controls.Add(verGroup[i]); 

它在verGroup [i] .Name處給我一個IndexOutofRangeException。但是索引是0,這肯定是它想要的嗎?創建動態控件

我也試過

verGroup = new GroupBox[5] 

但拋出錯誤的「不設置到對象的實例對象引用」。

如果有人能指出我正確的方向,將不勝感激。

+0

正在創建的數組,但從來沒有創建任何對象 – 2011-02-14 17:29:07

+0

嘗試添加verGroup [i] =新的組框() ;在你的第一次任務之前 – 2011-02-14 17:29:56

回答

5

由於量從0開始,並創建規格I,要創建的尺寸0,因此陣列的陣列可以在陣列中不索引任何東西,因爲它是一個長度爲0

第二個錯誤是因爲你沒有初始化組合框。你需要說verGroup [i] = new GroupBox();初始化它。

0

首先,你在這裏分配的GroupBox數組:

GroupBox[] verGroup; 
verGroup = new GroupBox[i]; 

然而,這並不在陣列內分配分組框中的值。這將需要分別處理:

GroupBox[] verGroup; 
verGroup = new GroupBox[i]; 
for(int gb = 0; gb < i; ++gb) 
    verGroup[gb] = new GroupBox(); // This creates the individual group box elements 

而且,如果i是0,你說創造零個框,然後試圖訪問第一(verGroup[0]是第一元素),這將失敗。你可能需要:

GroupBox[] verGroup; 
verGroup = new GroupBox[i+1]; 
for(int gb = 0; gb < verGroup.Length; ++gb) 
    verGroup[gb] = new GroupBox(); // This creates the individual group box elements 
0

你的代碼很糟糕,你只需要創建一次數組。那麼你需要實例化數組中的每個項目。

verGroup[] = new GroupBox[amount]; 
for (int i = 0; i < amount; i++) 
{ 
    verGroup[i] = new GroupBox(); 
    //set values and add to controls 
} 
0
int i = amount; //amount will always start at 0 
    int j = i + 1; 

    GroupBox[] verGroup; 
    verGroup = new GroupBox[i]; 
    verGroup[i] = new GroupBox(); 

    verGroup[i].Name = "verGroup" + i.ToString(); 
    verGroup[i].Width = 400; 
    verGroup[i].Height = 120; 
    verGroup[i].Left = 5; 
    verGroup[i].Top = 5 + (verGroup[i].Height * i) + (10 * i); 
    verGroup[i].Text = "Verification #" + j.ToString(); 

    pnlVer.Controls.Add(verGroup[i]); 

你必須有一個很好的理由,爲什麼要創建一個數組