0

I want to get the object that created in struct. Showing the codes will explain it better though.

 private void Obstacle() 
    {

        obstacle_pos_x = obstacle_random_x.Next(1000);
        obstacle_pos_y = obstacle_random_y.Next(700);
        picture = new PictureBox 
        {
            Name = "pictureBox" + obstacle_numb,
            Size = new Size(32, 32),
            Location = new Point(obstacle_pos_x,obstacle_pos_y),               
            BackColor = Color.Black,
        };
        this.Controls.Add(picture);       
    }

This is the struct inside of Obstacle method. As you can see this method creates pictureboxes and I want to pull them into KeyPressEvents. Like, if I press W, all the pictureboxes that created by struct has to move -10(y axis).

else if (e.KeyCode == Keys.W)
        {
            y -= chrspeed;
            obstacle_numb++;
            Obstacle();
            for (int i = 0; i <= obstacle_numb; i++)
            {

            }
        }

Well this the event. But it just creates pictureboxes. For loop is empty, because I couldn't figure out what to do. I simply want to do something like that,

picture+obstacle_numb.Location = new Point(x,y); (I need this picture+obstacle_numb combination.)

But also know that it is imposible. foreach came up to my mind but I don't know how to use it. Maybe something like this can work if fixed.

foreach(PictureBox objects from picture) //It doesn't work too.

I'm stuck right now and waiting for your help. Thanks in advance.

  • you've been very close: ```foreach(PictureBox pict in this.Controls) { pict.Location = new Point(pict.X, pict.Y-10); }``` – gofal3 Nov 07 '18 at 20:24
  • It tries to convert all the controls to pictureBox. It tried to convert panel into picturebox and gave error. I think we need to block all the controls except picturebox. I guess this.Controls is not enough by itself. It needs something after. – Yunus Derici Nov 08 '18 at 13:43
  • if you are adding ```using System.Linq``` to your usings, then you could filter the controls by type: ```foreach(var pict in this.Controls.OfType() {...}``` – gofal3 Nov 08 '18 at 14:11
  • It did work. But is there any code for exception? Like, I want to move all the pictureboxes but only picturebox1 has to be free. Thanks by the way. – Yunus Derici Nov 08 '18 at 14:28
  • I will post it as an answer – gofal3 Nov 08 '18 at 20:39

1 Answers1

1

The easiest would be to iterate all the child controls that are of type PictureBox:

...
foreach (var pict in this.Controls.OfType<PictureBox>())
{
    // pict is now a Picturebox, you can access all its properties as you have constructed it
    // the name was constructed that way: Name = "pictureBox" + obstacle_numb,
    if (pict.Name != "pictureBox1")
    {
        pict.Location = new Point(pict.X, pict.Y-10);
    }
}
gofal3
  • 1,213
  • 10
  • 16