2016-04-15 111 views
1

我想顯示13個圖片框,但是,它最後只有最後一個可見。 所以我想知道如果我做錯了。顯示圖片框陣列

以下代碼從資源文件夾中獲取圖像。

var testP = new PictureBox(); 
for (int i = 0; i < 13; i++) 
{ 
    testP.Width = 65;         
    testP.Height = 80; 
    testP.BorderStyle = BorderStyle.None; 
    testP.SizeMode = PictureBoxSizeMode.StretchImage; 
    test[i] = getImage(testP, testPTemp[i]);    
} 

下面的代碼試圖顯示13位圖片移動的位置。

這兩個代碼段應該能夠執行該操作。

test = new PictureBox[13];  
for (var i = 0; i < 13; i++) 
{ 
    test[i].Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + testTemp[i]);  
    test[i].Left = 330;  
    test[i].Top = 500;  
    test[i].Location = new Point(test[i].Location.X + 0 * displayShift, test[i].Location.Y); 
    this.Controls.Add(test[i]); 
} 

這裏是的getImage()

private PictureBox getImage(PictureBox pB, string i)    // Get image based on the for loop number (i) 
    { 
     pB.Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + i);   // Get the embedded image 
     pB.SizeMode = PictureBoxSizeMode.StretchImage; 
     return pB; 
    } 
+1

你想達到什麼目的? – Aybe

+0

@Aybe我試圖展示13 pictureBox,但它只顯示我最後一個,所以我想知道如果我做錯了。順便說一句,感謝您的回覆 – Edwardhk

+0

是的,但你如何顯示,水平,垂直等...解釋*確切*你需要什麼。 – Aybe

回答

1

我敢肯定有所有的PictureBox控件,但他們都在同一位置,以便他們在撒謊彼此上方。這就是爲什麼只有最後一個對你來說是可見的。

我想你應該用i變量替換0。

test[i].Location = new Point(test[i].Location.X + i * displayShift, test[i].Location.Y); this.Controls.Add(test[i]); 
+0

這是我在調試時犯的一個錯誤, 謝謝指出! – Edwardhk

1

很難根據您提供的代碼來判斷確切的問題。一個可能的問題是,當您創建PictureBox es時,只能在for循環之前創建一個實例,然後使用該實例的引用填充該數組。另一種可能性是,當您計算控件的X位置時,您將乘以0,這總是會導致0(意味着所有控件位於位置330)。

下面是代碼,將基本上實現你正在嘗試,但沒有你所有的代碼,我不能給你一個更具體的例子。

在類

const int PICTURE_WIDTH = 65; 
const int PICTURE_HEIGHT = 85; 

你內心功能

//Loop through each image 
for(int i = 0; i < testTemp[i].length; i++) 
{ 
    //Create a picture box 
    PictureBox pictureBox = new PictureBox(); 

    pictureBox.BorderStyle = BorderStyle.None; 
    pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; 

    //Load the image date 
    pictureBox.Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + testTemp[i]); 

    //Set it's size 
    pictureBox.Size = new Size(PICTURE_WIDTH, PICTURE_HEIGHT); 

    //Position the picture at (330,500) with a left offset of how many images we've gone through so far 
    pictureBox.Location = new Point(330 + (i * PICTURE_WIDTH), 500); 

    //Add the picture box to the list of controls 
    this.Controls.Add(pictureBox); 
} 

如果您需要保留的圖片框列表,只是在循環之前創建一個新的列表,並添加每個pictureBox到循環內的列表。如果要添加這些PictureBox es的控件/窗口需要向左或向右滾動以查看所有圖像,請將AutoScroll屬性設置爲true

+0

omg ...不能相信你用這樣乾淨的代碼解決我的問題! 謝謝你! – Edwardhk