我必須通過創建圖片框的數組:灌裝與pictureboxes數組
PictureBox[] places = new PictureBox[100];
我需要一些圖片框我有我的形式來填補它。有沒有辦法以編程方式填寫陣列或者我將需要使用:
places[0] = pictureBox1;
...
我必須通過創建圖片框的數組:灌裝與pictureboxes數組
PictureBox[] places = new PictureBox[100];
我需要一些圖片框我有我的形式來填補它。有沒有辦法以編程方式填寫陣列或者我將需要使用:
places[0] = pictureBox1;
...
在我的第一個例子中,我假設你想把你的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;
}
}
}
}
PictureBox[] places = this.Controls.OfType<PictureBox>().ToArray();
這讓你在控制器中定義的每個圖片框/表格
this refers to the Form
有沒有辦法不選擇一些圖片框? – codythecoder
是的,只需在表達式中放置一個where子句 – TGH
這是的WinForms? – Amy
我在visual studio 2013中使用C#編寫了可視化表單。 – codythecoder