В моем первом примере, сделав предположение, что вы хотите поместить свои PictureBoxes в массив в том порядке, в котором они были созданы 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;
}
}
}
}
Является ли это WinForms? – Amy
Я использую C# в visual studio 2013 с визуальным редактором формы. – codythecoder