2015-11-05 24 views
-1

我不明白我在做什麼錯,但當我試圖循環訪問這個picturebox創建數組時,我得到了這個錯誤。因此,我使用了嘗試和抓住來縮小它,但我仍然不知道什麼是錯的?C#在圖片框數組中循環 - NullReferenceException?

private System.Windows.Forms.PictureBox[] imgVictim = new PictureBox[3]; //array for victim images 
public void victimsRun() 
{ 
    victimTimer.Enabled = true; //starts the timer 

    PictureBox[] victim = new PictureBox[3]; 
    for (int i = 0; i < imgVictim.Length; i++) // 0 - 2 
    { 

     try 
     { 
      imgVictim[i].Image = Image.FromFile("victim" + i.ToString() + ".png"); 
     } 
     catch (NullReferenceException) 
     { 
      MessageBox.Show("NULL EXECEPTION!"); 
     } 
     MessageBox.Show(i.ToString()); 
    } 
} 

任何人都可以幫助我嗎?

+3

創建3 PictureBox的陣列並不意味着你已經創建了3 PictureBox的前創建的每個圖片框。 – Steve

+2

提示:你相信你顯示的代碼創建了多少個'PictureBox' *實例?你在哪裏調用任何'PictureBox'構造函數? –

+0

我沒有爲PictureBox創建任何構造函數,是否需要?感謝您的快速反應思想。 – Harry

回答

1

你需要使用它

imgVictim[i] = new PictureBox(); 

試試這個

private System.Windows.Forms.PictureBox[] imgVictim = new PictureBox[3]; //array for victim images 
public void victimsRun() 
{ 
    victimTimer.Enabled = true; //starts the timer 
    string fileName = ""; 
    PictureBox[] victim = new PictureBox[3]; 
    for (int i = 0; i < imgVictim.Length; i++) // 0 - 2 
    { 
     try 
     { 
      fileName = "victim" + i.ToString() + ".png"; 
      if (System.IO.File.Exists(fileName)) 
      { 
       imgVictim[i] = new PictureBox(); 
       imgVictim[i].Image = Image.FromFile("victim" + i.ToString() + ".png"); 
      } 
      else 
      { 
       // file does not exist or needs a path in front of it 
      } 
     } 
     catch (NullReferenceException) 
     { 
      MessageBox.Show("NULL EXECEPTION!"); 
     } 
    } 
} 
+0

我仍然遇到異常。 – Harry

+0

我在第一次回覆中添加了第二個代碼示例,看看是否有幫助。我可能無法在微軟的會議上回復一段時間。 –