C# 通过代码创建多个PictureBox-只有一个可见

C# 通过代码创建多个PictureBox-只有一个可见,c#,picturebox,C#,Picturebox,我尝试使用以下代码绘制大量图像实例: PictureBox[] sprites = new PictureBox[100]; private void Game_Load(object sender, EventArgs e) { PictureBox mainSprite = new PictureBox(); Bitmap img = new Bitmap(SpriteTest.Properties.Resources.Image); //Load a png image

我尝试使用以下代码绘制大量图像实例:

PictureBox[] sprites = new PictureBox[100];

private void Game_Load(object sender, EventArgs e)
{
    PictureBox mainSprite = new PictureBox();
    Bitmap img = new Bitmap(SpriteTest.Properties.Resources.Image); //Load a png image

    mainSprite.Size = new Size(16, 16);
    mainSprite.Image = img;

    for(var i = 0; i < sprites.Length; i++)
    {
        sprites[i] = mainSprite;

        //Keeping it simple for now with a single row of sprites
        sprites[i].Location = new Point(i * 16, 8); 
    }

    Game.ActiveForm.Controls.AddRange(sprites);
}

我曾多次遇到过这个问题,尤其是当我试图以类似的方式创建许多GroupBox时。在我试图找到解决方案的过程中,我在网上搜索了几个小时,但始终没有找到任何解决方案。

您实际上只创建了一个
PictureBox的实例:

PictureBox mainSprite = new PictureBox();

...

for(var i = 0; i < sprites.Length; i++)
{
    sprites[i] = mainSprite;

您实际上只创建了一个
PictureBox
的实例:

PictureBox mainSprite = new PictureBox();

...

for(var i = 0; i < sprites.Length; i++)
{
    sprites[i] = mainSprite;

非常感谢你!作为补充说明,使用:Game.ActiveForm.Controls.AddRange(精灵)时根本没有显示任何内容。所以我简单地加了一句;这个.Controls.Add(sprites[i])可以完美地工作!非常感谢你!作为补充说明,使用:Game.ActiveForm.Controls.AddRange(精灵)时根本没有显示任何内容。所以我简单地加了一句;这个.Controls.Add(sprites[i])可以完美地工作!
for(var i = 0; i < sprites.Length; i++)
{
    PictureBox mainSprite = new PictureBox();
    mainSprite.Size = new Size(16, 16);
    mainSprite.Image = img;
    sprites[i] = mainSprite;
    ...
}