2013-07-31 34 views
2

我必須通過創建圖片框的數組:灌裝與pictureboxes數組

PictureBox[] places = new PictureBox[100]; 

我需要一些圖片框我有我的形式來填補它。有沒有辦法以編程方式填寫陣列或者我將需要使用:

places[0] = pictureBox1; 
... 
+0

這是的WinForms? – Amy

+0

我在visual studio 2013中使用C#編寫了可視化表單。 – codythecoder

回答

1

在我的第一個例子中,我假設你想把你的PictureBox放入數組中被創建pictureBox1 = places[0];等。第二個示例通過使用Tag屬性作爲索引來分配它們放置在數組中的順序,這是我通常用來將控件添加到數組的方式。

第一種方法

private void button1_Click(object sender, EventArgs e) 
{ 
    var places = new PictureBox[10]; // I used 10 as a test 
    for (int i = 0; i < places.Length; i++) 
    { 
     // This does the work, it searches through the Control Collection to find 
     // a PictureBox of the requested name. It is fragile in the fact the the 
     // naming has to be exact. 
     try 
     { 
      places[i] = (PictureBox)Controls.Find("pictureBox" + (i + 1).ToString(), true)[0]; 
     } 
     catch (IndexOutOfRangeException) 
     { 
      MessageBox.Show("pictureBox" + (i + 1).ToString() + " does not exist!"); 
     } 

    } 
} 

第二種方法

private void button2_Click(object sender, EventArgs e) 
{ 
    // This example is using the Tag property as an index 
    // keep in mind that the index will be one less than your 
    // total number of Pictureboxes also make sure that your 
    // array is sized correctly. 
    var places = new PictureBox[100]; 
    int index; 
    foreach (var item in Controls) 
    { 
     if (item is PictureBox) 
     { 
      PictureBox pb = (PictureBox)item; 
      if (int.TryParse(pb.Tag.ToString(), out index)) 
      { 
       places[index] = pb; 
      } 
     } 
    } 
} 
0

使用for循環:

var places = new PictureBox[100]; 
for (int i = 0; i < places.Length; i++) 
{ 
    places[i] = this.MagicMethodToGetPictureBox(); 
} 
+1

如何讓MagicMethodToGetPictureBox按順序返回圖片框?他已經在表格上有圖片框。 – Amy

+0

我想我誤解了OP的問題;我以爲他想知道如何初始化陣列...對不起! – Jwosty

2
PictureBox[] places = this.Controls.OfType<PictureBox>().ToArray(); 

這讓你在控制器中定義的每個圖片框/表格

this refers to the Form 
+0

有沒有辦法不選擇一些圖片框? – codythecoder

+0

是的,只需在表達式中放置一個where子句 – TGH