2016-05-13 27 views
-1

所以我試圖在用C#的WinForms匹配的遊戲。我看了這個MSDN項目:https://msdn.microsoft.com/en-us/library/dd553230.aspx。我用圖像列表替換了圖標列表。根據這篇文章,我的圖像應該每個圖像顯示兩次。但是每當它再次碰到相同的數字時,它就說它超出了界限,這就是我認爲正在發生的事情。這裏是我的代碼:的ImageList扔我在ImageList.RemoveAt outofbounds異常()

public frmMain() 
    { 
     InitializeComponent(); 
     imageInit(); 
     imgToLbl(); 
    } 

    Random rndImage = new Random(); 

    ImageList images = new ImageList(); 

    //list of file names 
    List<string> files = new List<string>() 
    { 
     "Bavaria", "Denemarken", "Engeland", 
     "Frankrijk", "Nederland", "oostenrijk", 
     "Polen", "Pruissen", "Rusland", "Schotland", 
     "Spanje", "Zweden" 
    }; 

    // Method to put the files into the imagelist 
    private void imageInit() 
    { 
     for(int i = 0; i < 12; i++) 
     { 
      images.Images.Add(files[i], Image.FromFile("../../images/" + files[i] + ".png")); 
     } 
    } 

    // method to assign the images to a label in my form 
    private void imgToLbl() 
    { 
     foreach (Control ctrl in tableLayoutPanel1.Controls) 
     { 
      Label imgLbl = ctrl as Label; 
      if (imgLbl != null) 
      { 
       int rndNum = rndImage.Next(images.Images.Count); 
       images.ImageSize = imgLbl.Size; 
       imgLbl.ImageList = images; 
       imgLbl.ImageIndex = rndNum; 
       imgLbl.ImageList.Images.RemoveAt(rndNum);// this is where the exception is being thrown 
      } 
     } 
    } 

以下是完整的例外:

類型 'System.ArgumentOutOfRangeException' 的未處理的異常出現在System.Windows.Forms.dll中

其他信息: InvalidArgument ='8'的值對'index'無效。

我有一種感覺,這應該很容易,但我無法弄清楚如何解決這個異常。還有另一件事。顏色都搞砸了,我不知道爲什麼。

原來這裏是:

enter image description here

這裏是搞砸了一個它在應用中展示:

enter image description here

有人可以幫我嗎?

+0

是什麼rndNum和ImageList.Images長度的價值? –

+0

它可以是任何東西,從0到12,當我運行它,它因人而異,所以我創造了 –

+0

隨機它應該是0至11 –

回答

3

看起來你正試圖從標籤ImageList中刪除你剛分配給它的圖像。您最終將最終以ImageList和Labels中的0個條目仍然引用索引。您imgLbl.ImageList的分配是參考到已經存在的ImageList對象,它不是克隆它,因此,當你將其從名單被刪除它已分配的實例的每個標籤的條目。你想克隆列表(或更好)保持1個完整列表,並確保你不要選擇相同的數字兩次。

1
  • 你正在破壞圖像的ImageList,但你還是想LablesListItems等來指代他們。這不能工作

只要任何控制或其他項目需要顯示它們,您需要保持它們。

你看,你是分配只是一個數字作爲ImageIndex。這點數量爲ImageList,因此圖像仍然需要有..

  • 另外:質量是由您選擇的images.ColorDepth限制。將其設置爲Depth32Bit!默認值只有Depth8Bit