C# 用图片盒填充数组
我有一组图片框,由以下人员创建:C# 用图片盒填充数组,c#,arrays,C#,Arrays,我有一组图片框,由以下人员创建: PictureBox[] places = new PictureBox[100]; 我需要用我表格中的一些图片框来填充它。是否有任何方法以编程方式填充数组,或者我需要使用: places[0] = pictureBox1; ... 使用for循环: var places = new PictureBox[100]; for (int i = 0; i < places.Length; i++) { places[i] = this.MagicMe
PictureBox[] places = new PictureBox[100];
我需要用我表格中的一些图片框来填充它。是否有任何方法以编程方式填充数组,或者我需要使用:
places[0] = pictureBox1;
...
使用for循环:
var places = new PictureBox[100];
for (int i = 0; i < places.Length; i++)
{
places[i] = this.MagicMethodToGetPictureBox();
}
var places=new PictureBox[100];
for(int i=0;i
在我的第一个示例中,我假设您希望按照创建顺序将pictureBox1=places[0]放入数组中代码>等。第二个示例通过使用标记属性作为索引来指定它们在数组中的放置顺序,这是我通常用于向数组添加控件的方式
第一种方法
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;
}
}
}
}
如何使
MagicMethodToGetPictureBox
按顺序返回图片框?他已经在表格上有了图片框。我想我误解了OP的问题;我以为他想知道如何初始化数组。。。对不起!有没有办法不选择一些图片框?是的,只需在表达式上加一个where子句即可。我正在visual studio 2013的visual form editor中使用C#。
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;
}
}
}
}