0

I am making a 2D randomly generated tile map, as part of my school project. I've made a picture box array dynamically to store individual tiles, and i want to be able to let the user click on a picturebox with an event raised only to that specific picturebox, but im having trouble with it. (my map is 40x40 which makes 1600 pictureboxes, i do realise that is really inefficient :) )

current_mapXY[0] = 20; //these are the sizes in x and y of the pictureboxes
current_mapXY[1] = 20;

for (int i = 0; i < 40; i++)
{
    for (int i2 = 0; i2 < 40; i2++)
    {
        map[i, i2] = new PictureBox();
        map[i, i2].SizeMode = PictureBoxSizeMode.StretchImage;
        map[i, i2].Location = new System.Drawing.Point(current_mapXY[0] + (nextxy * i), current_mapXY[1] + (nextxy * i2));
        map[i, i2].Size = new System.Drawing.Size(current_mapXY[0], current_mapXY[1]);
        this.Controls.Add(map[i, i2]);
        progressBar1.Increment(1);
    }
}

Then after texturing i am trying to throw an event for each picturebox.

for (int i = 0; i < 40; i++)
{
    for (int i2 = 0; i2 < 40; i2++)
    {
        map[i, i2].Click += (a, b) => pic_click(sender, e, (i + "." + i2));
    }
}

private void pic_click(object sender, EventArgs e, string xy)
{ 
    MessageBox.Show(xy); 
}

What happens when i click a picturebox in runtime, is a messagebox with "40.40", but i want to be able to identify every picturebox. Thanks for any help in advance!

vgru
  • 49,838
  • 16
  • 120
  • 201
Deivis
  • 27
  • 3
  • Use `Sender` like this: http://stackoverflow.com/questions/35528548/detect-right-click-on-every-picturebox-on-the-form – Salah Akbari Oct 07 '16 at 11:22
  • Controls have a Name property. You could set it to "Pic" + i.ToString() + "_" + i2.ToString() in the creation loop. Then you can retrieve which picture has been clicked using the sender parameter (it is the picturebox clicked) – Steve Oct 07 '16 at 11:26
  • Your problem is related to the way variables are captured in lambdas (see the [duplicate](http://stackoverflow.com/q/271440/69809)). So either create temporary copies of `i` and `i2` (btw. why not `x` and `y`?) before creating the closure, or use the first (`sender`) event parameter to differentiate between controls. On a side note, you might want to try creating a custom control and paint the tiles yourself in a single run to make the whole thing more efficient. – vgru Oct 07 '16 at 11:42
  • Keep in mind that the actual sender object in your code is in the `a` variable, I don't know where the `sender` variable came from. You can also use the `PictureBox.Tag` property to store the actual `(x, y)` point for each `PictureBox` separately. – vgru Oct 07 '16 at 11:48

0 Answers0